<?php
namespace app\index\controller;


use app\index\model\DealcomModel;
use app\index\model\DeptModel;
use app\index\model\EnginBaoModel;
use app\index\model\EnginJianModel;
use app\index\model\EnginModel;
use app\index\model\EnginMuModel;
use app\index\model\EnginShiModel;
use app\index\model\EnginTempModel;
use app\index\model\EnginTingModel;
use app\index\model\EnginYueModel;
use app\index\model\FileModel;
use app\index\model\FlowBillModel;
use app\index\model\FlowLogModel;
use app\index\model\UserModel;
use app\index\model\UserRoleModel;
use app\index\relevan\CertRelevan;
use app\index\relevan\EnginRelevan;
use app\index\service\EnginService;
use app\index\service\FlowService;
use app\index\service\MenuService;
use app\index\service\OptService;
use app\index\service\UserService;
use app\index\service\WorkerService;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\facade\Env;
use think\File;
use think\Request;

class Engin extends Common
{
    protected $movePath = '../infoasset';
    protected $importPath = './importtmp';

    public function list_engin(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.areas','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['engintype']) && !empty($param['engintype'])){
            $where[] = ['e.engintype','=', $param['engintype']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['startdt']) && !empty($param['startdt'])){
            $where[] = ['e.startdt','between', explode(' - ', $param['startdt'])];
        }
        if(isset($param['enddt']) && !empty($param['enddt'])){
            $where[] = ['e.enddt','between', explode(' - ', $param['enddt'])];
        }

        $state = (new EnginService())->get_engin_state();
        $data['state'] = $state;
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_engintype'] = isset($param['engintype']) ? $param['engintype'] : '';


        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['state_name'] = (new EnginService())->get_engin_state_name_tag($item['id'], $item['state']);
                $item['state_name_mob'] = (new EnginService())->get_engin_state_name($item['id'], $item['state']);
                $item['engintype'] = (new OptService())->get_base_showname('engin_engintype', $item['engintype']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入项目名称');
            }
            if((new EnginService())->check_engin_name($param['name'])){
                return outputJson(4000, '项目名称已存在');
            }
            if($param['state'] == ''){
                return outputJson(4000, '请选择项目状态');
            }


            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            $tempid = (int)$param['tempid'];


            Db::startTrans();
            try {
                $id = EnginModel::insertGetId($param);

                $muid = EnginMuModel::insertGetId([
                    'comid' => $param['comid'],
                    'deptid' => $param['deptid'],
                    'chanid' => $param['chanid'],
                    'created_user' => $param['created_user'],
                    'created_at' => $param['created_at'],
                    'enginid' => $id,
                    'pid' => 0,
                    'level' => 1,
                    'sort' => 0,
                    'auth' => '',
                    'ismu' => 0,
                    'name' => $param['name'],
                ]);
                EnginMuModel::where(['id'=>$muid])->update(['parents'=>$muid]);

                if($tempid > 0){
                    (new EnginService())->create_engin_temp_info($muid, $tempid, $id);
                }

                (new OptService())->relation_file($files,'engin',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin', $id, '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
            $data['areas'] = (new OptService())->get_city_cader();
            $data['state'] = (new EnginService())->get_engin_state();
            $data['tempid'] = EnginTempModel::field('id,name')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>0])
                ->select()->toArray();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入项目名称');
            }
            if((new EnginService())->check_engin_name($param['name'], $param['id'])){
                return outputJson(4000, '项目名称已存在');
            }
            if($param['state'] === ''){
                return outputJson(4000, '请选择项目状态');
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);


            Db::startTrans();
            try {
                EnginModel::update($param);

                EnginMuModel::where(['enginid'=>$param['id'],'pid'=>0])->update(['name'=>$param['name']]);

                (new OptService())->relation_file($files,'engin',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $data['data']['jian_unit_info'] = DealcomModel::where('id','in',$data['data']['jian_unit'])->select()->toArray();
            $data['data']['she_unit_info'] = DealcomModel::where('id','in',$data['data']['she_unit'])->select()->toArray();
            $data['data']['kan_unit_info'] = DealcomModel::where('id','in',$data['data']['kan_unit'])->select()->toArray();
            $data['data']['shi_unit_info'] = DealcomModel::where('id','in',$data['data']['shi_unit'])->select()->toArray();
            $data['data']['li_unit_info'] = DealcomModel::where('id','in',$data['data']['li_unit'])->select()->toArray();
            $data['data']['yun_unit_info'] = DealcomModel::where('id','in',$data['data']['yun_unit'])->select()->toArray();
            $data['data']['gong_unit_info'] = DealcomModel::where('id','in',$data['data']['gong_unit'])->select()->toArray();
            $data['data']['zhi_unit_info'] = DealcomModel::where('id','in',$data['data']['zhi_unit'])->select()->toArray();

            $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
            $data['areas'] = (new OptService())->get_city_cader();
            $data['state'] = (new EnginService())->get_engin_state();
            $data['files'] = (new OptService())->get_file('engin', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function ting_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            unset($param['list']);

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                EnginModel::update($param);

                EnginTingModel::where(['enginid'=>$param['id']])->delete();
                foreach ($list as $item){
                    $item['enginid'] = $param['id'];
                    EnginTingModel::insert($item);
                }

                (new OptService())->add_flow_log('停工', 'engin', $param['id']);
                (new OptService())->add_log_list('停工', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $tinglist = EnginTingModel::where(['enginid'=>$data['data']['id']])->select()->toArray();
            $data['tinglist'] = $tinglist;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function setmu_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $engin = EnginModel::where(['id'=>$param['id']])->find();

            Db::startTrans();
            try {

                //删除原目录和上报文件
                EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);

                $muid = EnginMuModel::insertGetId([
                    'comid' => $engin['comid'],
                    'deptid' => $engin['deptid'],
                    'chanid' => $engin['chanid'],
                    'created_user' => $this->userinfo['id'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'enginid' => $engin['id'],
                    'pid' => 0,
                    'level' => 1,
                    'sort' => 0,
                    'auth' => '',
                    'ismu' => 0,
                    'name' => $engin['name'],
                ]);
                EnginMuModel::where(['id'=>$muid])->update(['parents'=>$muid]);
                EnginModel::where(['id'=>$param['id']])->update(['tempid'=>$param['tempid']]);

                (new EnginService())->create_engin_temp_info($muid, $param['tempid'], $engin['id']);

                (new OptService())->add_flow_log('设置资料模板库', 'engin', $param['id']);
                (new OptService())->add_log_list('设置资料模板库', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['tempid'] = EnginTempModel::field('id,name')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>0])
                ->order("id DESC")->select()->toArray();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_engin(Request $request){
        $param = $request->post();
        $data = EnginModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            EnginModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin', $data['id'], '项目');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }
        $data['data']['engintype'] = (new OptService())->get_base_showname('engin_engintype', $data['data']['engintype']);
        $data['data']['state_name'] = (new EnginService())->get_engin_state_name($data['data']['id'], $data['data']['state']);
        $data['data']['tempid_name'] = EnginTempModel::where(['id'=>$data['data']['tempid']])->value('name');


        $data['data']['jian_unit_name'] = DealcomModel::get_name_by_ids($data['data']['jian_unit']);
        $data['data']['she_unit_name'] = DealcomModel::get_name_by_ids($data['data']['she_unit']);
        $data['data']['kan_unit_name'] = DealcomModel::get_name_by_ids($data['data']['kan_unit']);
        $data['data']['shi_unit_name'] = DealcomModel::get_name_by_ids($data['data']['shi_unit']);
        $data['data']['li_unit_name'] = DealcomModel::get_name_by_ids($data['data']['li_unit']);
        $data['data']['yun_unit_name'] = DealcomModel::get_name_by_ids($data['data']['yun_unit']);
        $data['data']['gong_unit_name'] = DealcomModel::get_name_by_ids($data['data']['gong_unit']);
        $data['data']['zhi_unit_name'] = DealcomModel::get_name_by_ids($data['data']['zhi_unit']);


        $data['data']['jian_unit_arr'] = DealcomModel::where('id','in',$data['data']['jian_unit'])->select()->toArray();
        $data['data']['she_unit_arr'] = DealcomModel::where('id','in',$data['data']['she_unit'])->select()->toArray();
        $data['data']['kan_unit_arr'] = DealcomModel::where('id','in',$data['data']['kan_unit'])->select()->toArray();
        $data['data']['shi_unit_arr'] = DealcomModel::where('id','in',$data['data']['shi_unit'])->select()->toArray();
        $data['data']['li_unit_arr'] = DealcomModel::where('id','in',$data['data']['li_unit'])->select()->toArray();
        $data['data']['yun_unit_arr'] = DealcomModel::where('id','in',$data['data']['yun_unit'])->select()->toArray();
        $data['data']['gong_unit_arr'] = DealcomModel::where('id','in',$data['data']['gong_unit'])->select()->toArray();
        $data['data']['zhi_unit_arr'] = DealcomModel::where('id','in',$data['data']['zhi_unit'])->select()->toArray();

        $data['files'] = (new OptService())->get_file('engin', $data['data']['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }


    public function list_dealcom_dao(Request $request){
        $data = [];
        $arr = (new EnginService())->get_dealcom_type();
        foreach ($arr as $kkk=>$vvv){
            $data[] = ['title'=>$vvv, 'value'=>$kkk];
        }
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_dealcom(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['deal.deleted_user','=', 0];
        $where[] = ['deal.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['deal.name|deal.zizhi|deal.faer|deal.fatel|deal.lianer|deal.liantel','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['deal.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['deal.type','=', $param['type']];
        }
        if(isset($param['zizhi']) && !empty($param['zizhi'])){
            $where[] = ['deal.zizhi','like', '%'.$param['zizhi'].'%'];
        }
        if(isset($param['faer']) && !empty($param['faer'])){
            $where[] = ['deal.faer','like', '%'.$param['faer'].'%'];
        }
        if(isset($param['fatel']) && !empty($param['fatel'])){
            $where[] = ['deal.fatel','like', '%'.$param['fatel'].'%'];
        }
        if(isset($param['lianer']) && !empty($param['lianer'])){
            $where[] = ['deal.lianer','like', '%'.$param['lianer'].'%'];
        }
        if(isset($param['liantel']) && !empty($param['liantel'])){
            $where[] = ['deal.liantel','like', '%'.$param['liantel'].'%'];
        }

        $data['type'] = (new EnginService())->get_dealcom_type();
        $data['is_type'] = isset($param['type']) ? $param['type'] : '';

        $data['data'] = DealcomModel::alias('deal')
            ->field('deal.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('dealcom', 'deal'))
            ->order('deal.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['type'] = (new EnginService())->get_dealcom_type_name($item['type']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('dealcom');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_dealcom(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入单位名称');
            }
            if((new EnginService())->check_dealcom_name($param['name'])){
                return outputJson(4000, '单位名称已存在');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择单位类型');
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                $id = DealcomModel::insertGetId($param);
                (new OptService())->relation_file($files,'dealcom',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'dealcom', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'dealcom', $id, '参建单位');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['type'] = (new EnginService())->get_dealcom_type();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function muladd_dealcom(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            Db::startTrans();
            try {
                foreach ($list as $item){
                    $item['comid'] = $this->userinfo['comid'];
                    $item['created_user'] = $item['updated_user'] = $this->userinfo['id'];
                    $item['created_at'] = $item['updated_at']= date('Y-m-d H:i:s');
                    $item['deptid'] = $this->userinfo['deptid'];
                    $item['chanid'] = (new UserService())->get_user_chanid();

                    $id = DealcomModel::insertGetId($item);

                    (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'dealcom', $id);
                    (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'dealcom', $id, '参建单位');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['type'] = (new EnginService())->get_dealcom_type();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_dealcom(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入单位名称');
            }
            if((new EnginService())->check_dealcom_name($param['name'], $param['id'])){
                return outputJson(4000, '单位名称已存在');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择单位类型');
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                DealcomModel::update($param);
                (new OptService())->relation_file($files,'dealcom',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'dealcom', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'dealcom', $param['id'], '参建单位');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = DealcomModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['type'] = (new EnginService())->get_dealcom_type();
            $data['files'] = (new OptService())->get_file('dealcom', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_dealcom(Request $request){
        $param = $request->post();
        $data = DealcomModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            DealcomModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);

            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'dealcom', $data['id'], '参建单位');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_dealcom(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = DealcomModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }
        $data['data']['type_name'] = (new EnginService())->get_dealcom_type_name($data['data']['type']);
        $data['files'] = (new OptService())->get_file('dealcom', $data['data']['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }



    public function list_enginbao_mu(Request $request){
        $enginid = $request->param('enginid', 0, 'int');
        $muid = $request->param('muid', 0, 'int');
        $haveshen = $request->param('haveshen', 0, 'int');

        $muid_Parents = EnginMuModel::where(['id'=>$muid])->value('parents');
        $sppaarr = explode(',', $muid_Parents);
        $status = $haveshen ? [0,1,2] : [1];



        $whereCan = [];
        if($this->userinfo['token_roletype'] != 1){
            $isJianer = (new EnginService())->check_user_is_jian($enginid);
            if(!$isJianer){
                $whereCan[] = ['dealid','=',$this->userinfo['dealid']];
            }
        }

        $data = EnginMuModel::field('id,pid,name as title,parents,ismu,ext,size,oripath,encpath,baonum,baoshennum')
            ->where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
            ->order('pid ASC, ismu ASC, sort ASC')->select()->toArray();


        foreach ($data as &$item){
            if(in_array($item['id'], $sppaarr)){
                $item['spread'] = true;
            }
//            $parentsName = (new EnginService())->get_mu_quanname($item['parents'], 1);
            $parentsName = '';
            $item['basicData'] = [
                'id'=>$item['id'],
                'pid'=>$item['pid'],
                'name'=>$item['title'],
                'ismu'=>$item['ismu'],
                'part'=>'dept',
                'parentsName'=>$parentsName,
                'ext'=>$item['ext'],
                'size'=>$item['size'],
                'oripath'=>$item['oripath'],
                'encpath'=>$item['encpath'],
            ];
            if($item['ismu'] > 0){
                $item['basicData']['noicon'] = 1;
                $item['title'] = '<span class="colorhong">【模板】</span>'.$item['title'];
            }


//            if($this->cominfo['iskutong'] == 1){
//                $sonsArr = EnginMuModel::where(Db::raw("find_in_set(".$item['id'].",`parents`)"))->where(['enginid'=>$enginid])->column('id');
//                $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                    ->where('status','in',$status)->where('muid','in',$sonsArr)->count();
//                $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//            }else if($this->cominfo['iskutong'] == 2){
//                if($item['pid'] == 0){
//                    $sonsArr = EnginMuModel::where(Db::raw("find_in_set(".$item['id'].",`parents`)"))->where(['enginid'=>$enginid])->column('id');
//                    $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                        ->where('status','in',$status)->where('muid','in',$sonsArr)->count();
//                    $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//                }
//                if($item['ismu'] > 0){
//                    $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                        ->where('status','in',$status)->where(['muid'=>$item['id']])->count();
//                    $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//                }
//            }else{
//                if($item['ismu'] > 0){
//                    $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                        ->where('status','in',$status)->where(['muid'=>$item['id']])->count();
//                    $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//                }
//            }

            if($haveshen){
                $item['title'] = $item['title'].'（<span class="colorlv">'.$item['baoshennum'].'</span>）';
            }else{
                $item['title'] = $item['title'].'（<span class="colorlv">'.$item['baonum'].'</span>）';
            }
        }
        $data = array_values(listToTree($data));




        $bonum = 0;
        if($this->userinfo['token_roletype'] != 1){
            $bonum = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                ->where(['enginid'=>$enginid,'status'=>9])
                ->where('dealid','=', $this->userinfo['dealid'])
                ->count();
        }else{
            $bonum = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                ->where(['enginid'=>$enginid,'status'=>9])
                ->count();
        }
        return json_encode([
            'status'=>['code'=>200,'message'=>"操作成功"],
            'data'=>$data,
            'code'=>2000,
            'token_roletype'=>$this->userinfo['token_roletype'],
            'bao_butauth'=>(new MenuService())->get_butauth('engin_bao'),
            'baoku_butauth'=>(new MenuService())->get_butauth('engin_baoku'),
            'bonum'=>$bonum,
            'msg'=>'请求成功',
        ]);
    }
    public function list_enginbaoku_mu(Request $request){
        $enginid = $request->param('enginid', 0, 'int');
        $muid = $request->param('muid', 0, 'int');
        $haveshen = $request->param('haveshen', 0, 'int');

        $muid_Parents = EnginMuModel::where(['id'=>$muid])->value('parents');
        $sppaarr = explode(',', $muid_Parents);
        $status = $haveshen ? [0,1,2] : [1];

        if($this->userinfo['token_roletype'] != 1){
            $dataDingId = EnginMuModel::field('*')
                ->where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
                ->where(['pid'=>0])
                ->value('id');

            $dataOne = EnginMuModel::field('id,parents')
                ->where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
                ->where(Db::raw("find_in_set(".$this->userinfo['dealid'].",`auth`)"))
                ->select()->toArray();


            $whereAAA = "id=".$dataDingId;
            if($dataOne){
                foreach ($dataOne as $onevv){
                    $parentsArr = explode(',', $onevv['parents']);
                    sleep(8);
                    if(count($parentsArr) == 3){
                        $whereAAA .= " or id=".$parentsArr[1];
                    }
                    $whereAAA .= " or find_in_set(".$onevv['id'].",parents)";
                }
            }


            $data = EnginMuModel::field('id,pid,name as title,parents,ismu,ext,size,oripath,encpath,baonum,baoshennum')
                ->where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
                ->where(Db::raw($whereAAA))
                ->order('pid ASC, ismu ASC, sort ASC')->select()->toArray();

        }else{
            $data = EnginMuModel::field('id,pid,name as title,parents,ismu,ext,size,oripath,encpath,baonum,baoshennum')
                ->where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
                ->order('pid ASC, ismu ASC, sort ASC')->select()->toArray();
        }





        foreach ($data as &$item){
            if(in_array($item['id'], $sppaarr)){
                $item['spread'] = true;
            }
//            $parentsName = (new EnginService())->get_mu_quanname($item['parents'], 1);
            $parentsName = '';
            $item['basicData'] = [
                'id'=>$item['id'],
                'pid'=>$item['pid'],
                'name'=>$item['title'],
                'ismu'=>$item['ismu'],
                'part'=>'dept',
                'parentsName'=>$parentsName,
                'ext'=>$item['ext'],
                'size'=>$item['size'],
                'oripath'=>$item['oripath'],
                'encpath'=>$item['encpath'],
            ];
            if($item['ismu'] > 0){
                $item['basicData']['noicon'] = 1;
                $item['title'] = '<span class="colorhong">【模板】</span>'.$item['title'];
            }


//            if($this->cominfo['iskutong'] == 1){
//                $sonsArr = EnginMuModel::where(Db::raw("find_in_set(".$item['id'].",`parents`)"))->where(['enginid'=>$enginid])->column('id');
//                $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                    ->where('status','in',$status)->where('muid','in',$sonsArr)->count();
//                $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//            }else if($this->cominfo['iskutong'] == 2){
//                if($item['pid'] == 0){
//                    $sonsArr = EnginMuModel::where(Db::raw("find_in_set(".$item['id'].",`parents`)"))->where(['enginid'=>$enginid])->column('id');
//                    $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                        ->where('status','in',$status)->where('muid','in',$sonsArr)->count();
//                    $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//                }
//                if($item['ismu'] > 0){
//                    $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                        ->where('status','in',$status)->where(['muid'=>$item['id']])->count();
//                    $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//                }
//            }else{
//                if($item['ismu'] > 0){
//                    $baonums = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'deleted_user'=>0])
//                        ->where('status','in',$status)->where(['muid'=>$item['id']])->count();
//                    $item['title'] = $item['title'].'（<span class="colorlv">'.$baonums.'</span>）';
//                }
//            }
            if($haveshen){
                $item['title'] = $item['title'].'（<span class="colorlv">'.$item['baoshennum'].'</span>）';
            }else{
                $item['title'] = $item['title'].'（<span class="colorlv">'.$item['baonum'].'</span>）';
            }
        }
        $data = array_values(listToTree($data));

        return json_encode([
            'status'=>['code'=>200,'message'=>"操作成功"],
            'data'=>$data,
            'code'=>2000,
            'token_roletype'=>$this->userinfo['token_roletype'],
            'bao_butauth'=>(new MenuService())->get_butauth('engin_bao'),
            'baoku_butauth'=>(new MenuService())->get_butauth('engin_baoku'),
            'msg'=>'请求成功',
        ]);
    }


    public function list_engin_bao_count(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.areas','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['engintype']) && !empty($param['engintype'])){
            $where[] = ['e.engintype','=', $param['engintype']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['startdt']) && !empty($param['startdt'])){
            $where[] = ['e.startdt','between', explode(' - ', $param['startdt'])];
        }
        if(isset($param['enddt']) && !empty($param['enddt'])){
            $where[] = ['e.enddt','between', explode(' - ', $param['enddt'])];
        }

        $state = (new EnginService())->get_engin_state();
        $data['state'] = $state;
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_engintype'] = isset($param['engintype']) ? $param['engintype'] : '';


        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_baoku', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){

                $whereArr = [];
                if($this->userinfo['token_roletype'] != 1){
                    if(!in_array($this->userinfo['dealid'], explode(',', $item['jian_unit']))){
                        $whereArr[] = ['dealid','=',$this->userinfo['dealid']];
                    }
                }
                $item['bao_num'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'deleted_user'=>0])->where($whereArr)->count();
                $item['bao_size'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'deleted_user'=>0])->where($whereArr)->sum('size');
                $item['bao_size'] = round($item['bao_size']/1024, 2);
                $item['bao_shen0'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'deleted_user'=>0])->where($whereArr)->where('status','in',[0,2])->count();
                $item['bao_shen1'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'status'=>1,'deleted_user'=>0])->where($whereArr)->count();
                $item['bao_shen9'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'status'=>9,'deleted_user'=>0])->where($whereArr)->count();

                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_bao(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bao.deleted_user','=', 0];
        $where[] = ['bao.comid','=',$this->userinfo['comid']];
        $where[] = ['bao.enginid','=',$param['enginid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['bao.name|user.realname','like', '%'.$param['keyword'].'%'];
        }

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['bao.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $where[] = ['bao.created_at','between', explode(' - ', $param['created_at'])];
        }


        $whStatus = [];
        if(isset($param['status']) && $param['status'] != ''){
            if($param['status'] == 0){
                $whStatus[] = ['bao.status','in', [0,2]];
            }else{
                $whStatus[] = ['bao.status','=', $param['status']];
            }
        }

        if(isset($param['muid']) && !empty($param['muid'])){
            $muidArr = EnginMuModel::where(Db::raw("find_in_set(".$param['muid'].",`parents`)"))
                ->where(['enginid'=>$param['enginid']])->column('id');
            $where[] = ['bao.muid','in', $muidArr];
        }


        if($this->userinfo['token_roletype'] != 1){
            $isJianer = (new EnginService())->check_user_is_jian($param['enginid']);
            if(!$isJianer){
                $where[] = ['bao.dealid','=',$this->userinfo['dealid']];
            }
        }



        $data['data'] = EnginBaoModel::alias('bao')
            ->field('bao.*,user.realname as created_user_name')
            ->join('user user','user.id=bao.created_user')
            ->where($where)
            ->where($whStatus)
            ->order('bao.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['token_roletype'] = $this->userinfo['token_roletype'];
                $item['status_name'] = (new EnginService())->get_bao_status_name($item);
                $item['muid_name'] = (new EnginService())->get_mu_quanname_byid($item['muid']);
                $item['dealid_name'] = DealcomModel::where(['id'=>$item['dealid']])->value('name');

                $item['isshen'] = false;
                if($item['isjian'] > 0){
                    if($item['status'] == 0){
                        if( (new EnginService())->check_is_lishen($item['enginid']) ){
                            $item['isshen'] = true;
                        }
                    }elseif ($item['status'] == 2){
                        if( (new EnginService())->check_is_guanshen() ){
                            $item['isshen'] = true;
                        }
                    }
                }else{
                    if($item['status'] == 0){
                        if( (new EnginService())->check_is_guanshen() ){
                            $item['isshen'] = true;
                        }
                    }
                }


                return $item;
            })->toArray();
        $data['enginname'] = EnginModel::where(['id'=>$param['enginid']])->value('name');
        $data['bonum'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where(['enginid'=>$param['enginid'],'status'=>9])->count();
        if($this->userinfo['token_roletype'] != 1){
            $data['bonum'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                ->where(['enginid'=>$param['enginid'],'status'=>9])
                ->where('dealid','=', $this->userinfo['dealid'])
                ->count();
        }else{
            $data['bonum'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                ->where(['enginid'=>$param['enginid'],'status'=>9])
                ->count();
        }



        $data['shen_all'] = EnginBaoModel::alias('bao')
            ->join('user user','user.id=bao.created_user')
            ->where($where)->count();
        $data['shen_zhong'] = EnginBaoModel::alias('bao')
            ->join('user user','user.id=bao.created_user')
            ->where($where)->where('bao.status','in', [0,2])->count();
        $data['shen_guo'] = EnginBaoModel::alias('bao')
            ->join('user user','user.id=bao.created_user')
            ->where($where)->where('bao.status','=', 1)->count();
        $data['shen_bo'] = EnginBaoModel::alias('bao')
            ->join('user user','user.id=bao.created_user')
            ->where($where)->where('bao.status','=', 9)->count();


        $data['butauth'] = (new MenuService())->get_butauth('engin_bao');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_bao(Request $request)
    {
        $enginid = $request->param('enginid',0,'int');
        $muid = $request->param('muid',0,'int');
        if(!$muid){
            $muid = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'pid'=>0])->value('id');
        }

        $yanbot =  $request->param('yanbot',0,'int');
        if($yanbot > 0){
            $existSon = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                ->where(['enginid'=>$enginid,'pid'=>$muid])->find();
            if($existSon){
                return outputJson(4000, '请选择最后一级子文件夹');
            }else{
                return outputJson(2000,lang('code_2000'));
            }
        }


        $isadd = $request->param('isadd',0,'int');
        $files = request()->file('files');
        $ismob = $request->param('ismob',0,'int');
        if($ismob){
            $files = [$files];
        }

        $is_want = (new EnginService())->check_want_lishen($enginid);

        Db::startTrans();
        try{
            foreach ($files as $file){
                $fileInfo = $file->getInfo();
                $filesize = round($fileInfo['size']/1024,2);
                $info = $file->validate([
                    'size'=>Config::get('service.upload.size'),'ext'=>Config::get('service.upload.ext')
                ])->move($this->movePath);

                if($info){
                    $ins = [];
                    $ins['comid'] = $this->userinfo['comid'];
                    $ins['isadd'] = $isadd;

                    if($isadd > 0){
                        $ins['status'] = 1;
                        $ins['isjian'] = 0;
                    }else{
                        $ins['status'] = 0;
                        if($is_want){
                            $ins['isjian'] = 1;
                        }else{
                            $ins['isjian'] = 0;
                        }
                    }

                    $ins['enginid'] = $enginid;
                    $ins['dealid'] = $this->userinfo['dealid'];
                    $ins['muid'] = $muid;
                    $ins['name'] = $fileInfo['name'];
                    $ins['ext'] =  strtolower($info->getExtension());
                    $ins['size'] = $filesize;
                    $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                    $ins['encpath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                    $ins['created_user'] =  $this->userinfo['id'];
                    $ins['created_at'] =  date('Y-m-d H:i:s');
                    $ins['updated_at'] =  date('Y-m-d H:i:s');
                    $ins_id = EnginBaoModel::insertGetId($ins);

                    $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                    if(EnginBaoModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                        throw new Exception("上传失败");
                    }

                    (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_bao', $ins_id);
                    (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_bao', $ins_id, '上报文件');

                    $enginInfo = EnginModel::where(['id'=>$enginid])->find();
                    if($is_want){
                        $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                    }else{
                        $shenUserArr = (new EnginService())->get_guanuser();
                    }
                    foreach($shenUserArr as $uid){
                        (new WorkerService())->add_worker($uid, '上报文件',$enginInfo['name'], $ins_id, 'engin_bao');
                    }


                    (new EnginService())->set_engin_baonum($muid);

                }else{
                    throw new Exception("上传失败");
                }
            }

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function add_engin_bao222(Request $request)
    {
        $enginid = $request->param('enginid',0,'int');
        $muid = $request->param('muid',0,'int');
        if(!$muid){
            $muid = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$enginid,'pid'=>0])->value('id');
        }

        $yanbot =  $request->param('yanbot',0,'int');
        if($yanbot > 0){
            $existSon = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                ->where(['enginid'=>$enginid,'pid'=>$muid])->find();
            if($existSon){
                return outputJson(4000, '请选择最后一级子文件夹');
            }else{
                return outputJson(2000,lang('code_2000'));
            }
        }


        $isadd = $request->param('isadd',0,'int');
        $files = request()->file('files');
        $ismob = $request->param('ismob',0,'int');
        if($ismob){
            $files = [$files];
        }


        $zongNum = count($files);
        $succNum = 0;

        $is_want = (new EnginService())->check_want_lishen($enginid);

        try{
            foreach ($files as $file){
                $fileInfo = $file->getInfo();
                $filesize = round($fileInfo['size']/1024,2);
                $info = $file->validate([
                    'size'=>Config::get('service.upload.size'),'ext'=>Config::get('service.upload.ext')
                ])->move($this->movePath);

                if($info){
                    $ins = [];
                    $ins['comid'] = $this->userinfo['comid'];
                    $ins['isadd'] = $isadd;

                    if($isadd > 0){
                        $ins['status'] = 1;
                        $ins['isjian'] = 0;
                    }else{
                        $ins['status'] = 0;
                        if($is_want){
                            $ins['isjian'] = 1;
                        }else{
                            $ins['isjian'] = 0;
                        }
                    }

                    $ins['enginid'] = $enginid;
                    $ins['dealid'] = $this->userinfo['dealid'];
                    $ins['muid'] = $muid;
                    $ins['name'] = $fileInfo['name'];
                    $ins['ext'] =  strtolower($info->getExtension());
                    $ins['size'] = $filesize;
                    $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                    $ins['encpath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                    $ins['created_user'] =  $this->userinfo['id'];
                    $ins['created_at'] =  date('Y-m-d H:i:s');
                    $ins['updated_at'] =  date('Y-m-d H:i:s');
                    $ins_id = EnginBaoModel::insertGetId($ins);

                    $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                    if(EnginBaoModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                        throw new Exception("上传失败");
                    }

                    (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_bao', $ins_id);
                    (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_bao', $ins_id, '上报文件');

                    $succNum += 1;

                    $enginInfo = EnginModel::where(['id'=>$enginid])->find();
                    if($is_want){
                        $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                    }else{
                        $shenUserArr = (new EnginService())->get_guanuser();
                    }
                    foreach($shenUserArr as $uid){
                        (new WorkerService())->add_worker($uid, '上报文件',$enginInfo['name'], $ins_id, 'engin_bao');
                    }
                }else{
                    throw new Exception("上传失败");
                }
            }
        }catch (\Exception $e){
            $failNum = $zongNum - $succNum;
            return outputJson(4444,'本次共上传文件'.$zongNum.'个，成功'.$succNum.'个，失败'.$failNum.'个！');
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function chong_engin_bao(Request $request)
    {
        $file = request()->file("file");
        try{
            $fileInfo = $file->getInfo();
            $filesize = round($fileInfo['size']/1024,2);
            $info = $file->validate([
                'size'=>Config::get('service.upload.size'),'ext'=>Config::get('service.upload.ext')
            ])->move($this->movePath);
            if($info){
                $ins = [];
                $ins['comid'] = $this->userinfo['comid'];
                $ins['name'] =  $fileInfo['name'];
                $ins['ext'] =  strtolower($info->getExtension());
                $ins['size'] = $filesize;
                $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                $ins['created_user'] =  $this->userinfo['id'];
                $ins['created_at'] =  date('Y-m-d H:i:s');
                $ins_id = FileModel::insertGetId($ins);

                $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                if(FileModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                    throw new Exception("上传失败");
                }

                $return_data = $ins;
                $return_data['id'] = $ins_id;
                $return_data['created_user_name'] =  $this->userinfo['realname'];
                $return_data['encpath'] = $encpath;
                unset($return_data['oripath']);
            }else{
                throw new Exception("上传失败");
            }
        }catch (\Exception $e){
            $return_data['msg'] = $e->getMessage();
            return outputJson(4000,lang('code_4000'), $return_data);
        }
        return outputJson(2000,lang('code_2000'), $return_data);
    }
    public function edit_engin_bao(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $oldInfo = EnginBaoModel::where(['id'=>$param['id']])->find();
            $is_want = (new EnginService())->check_want_lishen($oldInfo['enginid']);

            $param['status'] = 0;
            if($is_want){
                $param['isjian'] = 1;
            }else{
                $param['isjian'] = 0;
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                if($param['fileid']){
                    $fileinfo = FileModel::where(['id'=>$param['fileid']])->find();

                    $param['name'] = $param['name'].'.'.$fileinfo['ext'];
                    $param['ext'] = $fileinfo['ext'];
                    $param['size'] = $fileinfo['size'];
                    $param['oripath'] = $fileinfo['oripath'];
                    $param['encpath'] = encrypt($param['id'], 'E', Config::get('service.info_key'));
                }else{
                    $param['name'] = $param['name'].'.'.$oldInfo['ext'];
                }

                EnginBaoModel::update($param);


                $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                if($is_want){
                    $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                }else{
                    $shenUserArr = (new EnginService())->get_guanuser();
                }
                foreach($shenUserArr as $uid){
                    (new WorkerService())->add_worker($uid, '上报文件',$enginInfo['name'], $param['id'], 'engin_bao');
                }


                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_bao', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_bao', $param['id'], '文件上报');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginBaoModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['data']['name'] = mb_substr($data['data']['name'], 0, mb_strlen($data['data']['name'])-4);


            $data['data']['muid_name'] = (new EnginService())->get_mu_quanname_byid($data['data']['muid']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function edit_engin_bao_two(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['muid'])){
                return outputJson(4000, '请选择位置');
            }
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $oldInfo = EnginBaoModel::where(['id'=>$param['id']])->find();

            $param['name'] = $param['name'].'.'.$oldInfo['ext'];

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                EnginBaoModel::update($param);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_bao', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_bao', $param['id'], '文件上报');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginBaoModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['data']['name'] = mb_substr($data['data']['name'], 0, mb_strlen($data['data']['name'])-4);

            $data['muid'] = (new EnginService())->get_engin_mu_xmselect(0,$data['data']['enginid']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_engin_bao(Request $request){
        $param = $request->post();
        $data = EnginBaoModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            EnginBaoModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);

            (new EnginService())->set_engin_baonum($data['muid']);

            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_bao', $data['id'], '文件上报');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin_bao(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginBaoModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }


        $data['muinfo'] = EnginMuModel::where(['id'=>$data['data']['muid']])->find();

        $data['data']['status_name'] = (new EnginService())->get_bao_status_tagname($data['data']);
        $data['data']['muid_name'] = (new EnginService())->get_mu_quanname_byid($data['data']['muid']);
        $data['data']['enginid_name'] = EnginModel::where(['id'=>$data['data']['enginid']])->value('name');
        $data['data']['created_user_name'] = UserModel::where(['id'=>$data['data']['created_user']])->value('realname');
        $data['data']['dealid_name'] = DealcomModel::where(['id'=>$data['data']['dealid']])->value('name');
        $isshen = false;
        if($data['data']['isjian'] > 0){
            if($data['data']['status'] == 0){
                if( (new EnginService())->check_is_lishen($data['data']['enginid']) ){
                    $isshen = true;
                }
            }elseif ($data['data']['status'] == 2){
                if( (new EnginService())->check_is_guanshen() ){
                    $isshen = true;
                }else{
                    if( (new EnginService())->check_is_jianshen($data['data']['enginid']) ){
                        $isshen = true;
                    }
                }
            }
        }else{
            if($data['data']['status'] == 0){
                if( (new EnginService())->check_is_guanshen() ){
                    $isshen = true;
                }else{
                    if( (new EnginService())->check_is_jianshen($data['data']['enginid']) ){
                        $isshen = true;
                    }
                }
            }
        }
        $data['isshen'] = $isshen;

        return outputJson(2000,lang('code_2000'), $data);
    }
    public function shen_engin_bao(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $oldInfo = EnginBaoModel::where(['id'=>$param['id']])->find();
            if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                return outputJson(4000, lang('code_4000'));
            }


            //  当 isjian > 0     status=0【待监理审核】  status=2【待管理员审核】 status=1【审核通过】  status=9【审核驳回】
            //  当 isjian = 0     status=0【待管理员审核】  status=1【审核通过】  status=9【审核驳回】

            $statusName = '';
            if($oldInfo['isjian'] > 0){
                if($oldInfo['status'] == 0){
                    if( !(new EnginService())->check_is_lishen($oldInfo['enginid']) ){
                        return outputJson(4000, lang('code_4000'));
                    }
                    $statusName = $param['status'] == 1 ? '通过[监理]' : '驳回[监理]';

                    if($param['status'] == 1){
                        $param['status'] = 2;
                    }
                }elseif ($oldInfo['status'] == 2){
                    if( !(new EnginService())->check_is_guanshen() ){
                        if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                            return outputJson(4000, lang('code_4000'));
                        }
                    }
                    $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
                }else{
                    return outputJson(4000, lang('code_4000'));
                }
            }else{
                if ($oldInfo['status'] == 0){
                    if( !(new EnginService())->check_is_guanshen() ){
                        if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                            return outputJson(4000, lang('code_4000'));
                        }
                    }
                    $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
                }else{
                    return outputJson(4000, lang('code_4000'));
                }
            }

            $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();

            Db::startTrans();
            try {
                EnginBaoModel::where(['id'=>$param['id']])->update(['status'=>$param['status']]);

                (new EnginService())->set_engin_baonum($oldInfo['muid']);


                if($param['status'] == 2){
                    $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                    foreach($shenUserArr as $uid){
                        (new WorkerService())->add_worker($uid, '文件上报',$enginInfo['name'], $oldInfo['id'], 'engin_bao');
                    }
                }


                (new OptService())->add_flow_log('审核', 'engin_bao', $param['id'], $statusName, $param['explain'], $param['files']);
                (new OptService())->add_log_list('审核', 'engin_bao', $param['id'], '文件上报');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function mulshen_engin_bao(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $ids = $request->post('ids','string','');

            Db::startTrans();
            try {

                $oldArr = EnginBaoModel::where('id','in',$ids)->select()->toArray();
                foreach ($oldArr as $oldInfo){
                    if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                        continue;
                    }

                    $statusName = '';
                    $status = $param['status'];
                    if($oldInfo['isjian'] > 0){
                        if($oldInfo['status'] == 0){
                            if( !(new EnginService())->check_is_lishen($oldInfo['enginid']) ){
                                continue;
                            }
                            $statusName = $status == 1 ? '通过[监理]' : '驳回[监理]';

                            if($status == 1){
                                $status = 2;
                            }
                        }elseif ($oldInfo['status'] == 2){
                            if( !(new EnginService())->check_is_guanshen() ){
                                if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                                    continue;
                                }
                            }
                            $statusName = $status == 1 ? '通过[管理员]' : '驳回[管理员]';
                        }else{
                            continue;
                        }
                    }else{
                        if ($oldInfo['status'] == 0){
                            if( !(new EnginService())->check_is_guanshen() ){
                                if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                                    continue;
                                }
                            }
                            $statusName = $status == 1 ? '通过[管理员]' : '驳回[管理员]';
                        }else{
                            continue;
                        }
                    }


                    EnginBaoModel::where(['id'=>$oldInfo['id']])->update(['status'=>$status]);

                    (new EnginService())->set_engin_baonum($oldInfo['muid']);


                    if($status == 2){
                        $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                        $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                        foreach($shenUserArr as $uid){
                            (new WorkerService())->add_worker($uid, '文件上报',$enginInfo['name'], $oldInfo['id'], 'engin_bao');
                        }
                    }

                    (new OptService())->add_flow_log('审核', 'engin_bao', $oldInfo['id'], $statusName, $param['explain']);
                    (new OptService())->add_log_list('审核', 'engin_bao', $oldInfo['id'], '文件上报');
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function list_engin_mu_xiabao(Request $request){
        $param = $request->post();

        $haveshen = $request->param('haveshen', 0, 'int');
        $status = $haveshen ? [0,1,2] : [1];

        $list = [];
        $ban = EnginMuModel::where(['id'=>$param['muid']])->find();
        $ban_quanname = (new EnginService())->get_mu_quanname($ban['parents'], 1);
        $ban['type'] = 'ban';
        $ban['title'] = '<span class="colorhong">【模板】</span>'.$ban['name'];
        $ban['title2'] = '【模板】'.$ban['name'];
        $ban['parentsName'] = $ban_quanname.'/'.$ban['name'];
        $list[] = $ban;




        $whereCan = [];
        if($this->userinfo['token_roletype'] != 1){
            $isJianer = (new EnginService())->check_user_is_jian($param['enginid']);
            if(!$isJianer){
                $whereCan[] = ['dealid','=',$this->userinfo['dealid']];
            }
        }


        $baoList = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['enginid'],'deleted_user'=>0])
            ->where(['muid'=>$param['muid']])->where('status','in',$status)->where($whereCan)->order('created_at DESC')->select()->toArray();
        foreach ($baoList as &$vvv){
            $vvv['type'] = 'bao';
            $vvv['title'] = $vvv['name'];
            $vvv['title2'] = $vvv['name'];
            if($vvv['status'] != 1){
                $vvv['title'] = '<span class="colorhong">[审]</span>'.$vvv['name'];
                $vvv['title2'] = '[审]'.$vvv['name'];
            }
            $vvv['parentsName'] = $ban_quanname.'/'.$vvv['name'];
            $list[] = $vvv;
        }

        $data['status'] = true;
        $data['list'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_mu_xiabao_ku(Request $request){
        $param = $request->post();

        $haveshen = $request->param('haveshen', 0, 'int');
        $status = $haveshen ? [0,1,2] : [1];

        $list = [];
        $ban = EnginMuModel::where(['id'=>$param['muid']])->find();
        $ban_quanname = (new EnginService())->get_mu_quanname($ban['parents'], 1);
        $ban['type'] = 'ban';
        $ban['title'] = '<span class="colorhong">【模板】</span>'.$ban['name'];
        $ban['title2'] = '【模板】'.$ban['name'];
        $ban['parentsName'] = $ban_quanname.'/'.$ban['name'];
        $list[] = $ban;


        $whereZai = "";
        //参建单位角色：根据一级目录权限，查看右侧上报文件，无权限则提示无查看权限
        if($this->userinfo['token_roletype'] != 1){
            $banPararr = explode(',', $ban['parents']);
            $oneji = EnginMuModel::where(['id'=>$banPararr[1]])->find();
            $onejiauth = explode(',', $oneji['auth']);
            if(!in_array($this->userinfo['dealid'],$onejiauth)){
                return outputJson(2000,lang('code_2000'),['list'=>$list,'status'=>false]);
            }
        }

        $baoList = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['enginid'],'deleted_user'=>0])
            ->where(['muid'=>$param['muid']])->where('status','in',$status)->order('created_at DESC')->select()->toArray();
        foreach ($baoList as &$vvv){
            $vvv['type'] = 'bao';
            $vvv['title'] = $vvv['name'];
            $vvv['title2'] = $vvv['name'];
            if($vvv['status'] != 1){
                $vvv['title'] = '<span class="colorhong">[审]</span>'.$vvv['name'];
                $vvv['title2'] = '[审]'.$vvv['name'];
            }
            $vvv['parentsName'] = $ban_quanname.'/'.$vvv['name'];
            $list[] = $vvv;
        }

        $data['status'] = true;
        $data['list'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_engin_baoku_count(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.areas','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['engintype']) && !empty($param['engintype'])){
            $where[] = ['e.engintype','=', $param['engintype']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['startdt']) && !empty($param['startdt'])){
            $where[] = ['e.startdt','between', explode(' - ', $param['startdt'])];
        }
        if(isset($param['enddt']) && !empty($param['enddt'])){
            $where[] = ['e.enddt','between', explode(' - ', $param['enddt'])];
        }

        $state = (new EnginService())->get_engin_state();
        $data['state'] = $state;
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_engintype'] = isset($param['engintype']) ? $param['engintype'] : '';


        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_baoku', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['bao_num'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'deleted_user'=>0,'status'=>1])->count();
                $item['bao_size'] = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'deleted_user'=>0,'status'=>1])->sum('size');
                $item['bao_size'] = round($item['bao_size']/1024, 2);
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_baoku(Request $request){
        $param = $request->post();
        $type = $request->param('type',0, 'int');

        $whereBao = [];
        if(isset($param['name']) && !empty($param['name'])){
            $whereBao[] = ['bao.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $whereBao[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $whereBao[] = ['bao.created_at','between', explode(' - ', $param['created_at'])];
        }




        $muid = $request->param('muid',0, 'int');
        if(!$muid){
            $muid = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['enginid'],'pid'=>0,'deleted_user'=>0])->value('id');
        }
        $data['muinfo'] = EnginMuModel::where(['id'=>$muid])->find();
        $shangMuArr = (new EnginService())->get_mu_shang_quanauth($muid);

        $muList = [];
        if($type == 0){
            $muList = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['enginid'],'pid'=>$muid,'deleted_user'=>0])
                ->order('created_at ASC, id ASC')->select()->toArray();
        }
        $data['muList'] = $muList;


        $baoList = [];
        if($this->userinfo['token_roletype'] != 1){
            if(in_array($this->userinfo['dealid'], $shangMuArr)){
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.muid'=>$muid,'bao.deleted_user'=>0,'bao.status'=>1])->select()->toArray();
            }else{
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.muid'=>$muid,'bao.dealid'=>$this->userinfo['dealid'],'bao.deleted_user'=>0,'bao.status'=>1])->select()->toArray();
            }
        }else{
            if($type == 0){
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.muid'=>$muid,'bao.deleted_user'=>0,'bao.status'=>1])->select()->toArray();
            }else{
                $muSons = (new EnginService())->get_engin_mu_sonid($param['enginid'],$muid);
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.deleted_user'=>0,'bao.status'=>1])
                    ->where('bao.muid','in',$muSons)
                    ->select()->toArray();
            }

        }

        $data['baoList'] = $baoList;

        $data['enginname'] = EnginModel::where(['id'=>$param['enginid']])->value('name');

        $data['muArr'] = (new EnginService())->get_mu_shang_arr($muid);
        $data['butauth'] = (new MenuService())->get_butauth('engin_baoku');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_baoku2(Request $request){
        $param = $request->post();
        $type = $request->param('type',0, 'int');

        $whereBao = [];
        if(isset($param['name']) && !empty($param['name'])){
            $whereBao[] = ['bao.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $whereBao[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $whereBao[] = ['bao.created_at','between', explode(' - ', $param['created_at'])];
        }




        $muid = $request->param('muid',0, 'int');
        if(!$muid){
            $muid = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['enginid'],'pid'=>0,'deleted_user'=>0])->value('id');
        }
        $data['muinfo'] = EnginMuModel::where(['id'=>$muid])->find();
        $shangMuArr = (new EnginService())->get_mu_shang_quanauth($muid);

        $muList = [];
        if($type == 0){
            $muList = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['enginid'],'pid'=>$muid,'deleted_user'=>0])
                ->order('created_at ASC, id ASC')->select()->toArray();
            foreach ($muList as &$fff){
                if($fff['ismu'] > 0){
                    $fff['name'] = '【模板】'.$fff['name'];
                }

            }
        }
        $data['muList'] = $muList;


        $baoList = [];
        if($this->userinfo['token_roletype'] != 1){
            if(in_array($this->userinfo['dealid'], $shangMuArr)){
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.muid'=>$muid,'bao.deleted_user'=>0])->where('bao.status','in',[0,2])->select()->toArray();
            }else{
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.muid'=>$muid,'bao.dealid'=>$this->userinfo['dealid'],'bao.deleted_user'=>0])
                    ->where('bao.status','in',[0,2])->select()->toArray();
            }
        }else{
            if($type == 0){
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.muid'=>$muid,'bao.deleted_user'=>0])->where('bao.status','in',[1])->select()->toArray();
            }else{
                $muSons = (new EnginService())->get_engin_mu_sonid($param['enginid'],$muid);
                $baoList = EnginBaoModel::alias('bao')
                    ->field('bao.*')
                    ->join('user user','user.id=bao.created_user')
                    ->where(['bao.comid'=>$this->userinfo['comid'],'bao.enginid'=>$param['enginid']])->where($whereBao)
                    ->where(['bao.deleted_user'=>0])
                    ->where('bao.status','in',[1])
                    ->where('bao.muid','in',$muSons)
                    ->select()->toArray();
            }

        }

        $data['baoList'] = $baoList;

        $data['enginname'] = EnginModel::where(['id'=>$param['enginid']])->value('name');

        $data['muArr'] = (new EnginService())->get_mu_shang_arr($muid);
        $data['butauth'] = (new MenuService())->get_butauth('engin_bao');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_mu(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidInfo = EnginMuModel::where(['id'=>$param['pid']])->find();
            if(!$pidInfo){
                $pidInfo = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'enginid'=>$param['enginid'],'pid'=>0])->find();
            }

            $param['name'] = (new EnginService())->check_engin_mu_name($param['name'], $param['pid'], $param['enginid']);
            $param['parents'] = $pidInfo['parents'].',';
            $param['level'] = $pidInfo['level'] + 1;


            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                $id = EnginMuModel::insertGetId($param);

                $newParents = $pidInfo['parents'].','.$id;
                EnginMuModel::where(['id'=>$id])->update(['parents'=>$newParents]);


                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_mu', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_mu', $id, '文件夹');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->param('enginid',0, 'int');
            $pid = $request->param('pid',0, 'int');
            $pidInfo = EnginMuModel::where(['id'=>$pid])->find();
            $data['pid_name'] = (new EnginService())->get_mu_quanname($pidInfo['parents'], 1);
            $sort = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'pid'=>$pid,'deleted_user'=>0])
                ->order('sort DESC')->value('sort');
            $data['sort'] = ceil($sort)+1;

//            $engininfo = EnginModel::where(['id'=>$enginid])->find();
//            $authArr = [];
//            foreach (explode(',', $engininfo['jian_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['she_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['kan_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['shi_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                 if($dealName){
//                     $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                 }
//            }
//            foreach (explode(',', $engininfo['li_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                 if($dealName){
//                     $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                 }
//            }
//            foreach (explode(',', $engininfo['yun_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['gong_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['zhi_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            $data['authArr'] = $authArr;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin_mu(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $oldInfo = EnginMuModel::where(['id'=>$param['id']])->find();

            $param['name'] = (new EnginService())->check_engin_mu_name($param['name'], $oldInfo['pid'], $oldInfo['enginid'], $param['id']);
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                EnginMuModel::update($param);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_mu', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_mu', $param['id'], '文件夹');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginMuModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $pidInfo = EnginMuModel::where(['id'=>$data['data']['pid']])->find();
            $data['data']['pid_name'] = (new EnginService())->get_mu_quanname($pidInfo['parents'], 1);

//            $data['data']['authArr'] = explode(',', $data['data']['auth']);
//            $engininfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
//            $authArr = [];
//            foreach (explode(',', $engininfo['jian_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['she_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['kan_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['shi_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['li_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['yun_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['gong_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            foreach (explode(',', $engininfo['zhi_unit']) as $dealid){
//                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
//                if($dealName){
//                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
//                }
//            }
//            $data['authArr'] = $authArr;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function guan_engin_mu(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            Db::startTrans();
            try {

                foreach ($list as $vvv){
                    EnginMuModel::where(['id'=>$vvv['id']])->update(['auth'=>$vvv['auth']]);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->param('enginid',0, 'int');
            $one = EnginMuModel::field('id,id as value,name as title,name,level,auth')
                ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>0,'enginid'=>$enginid,'ismu'=>0])
                ->find();
            $one['auth'] = explode(',', $one['auth']);
            $children = EnginMuModel::field('id,id as value,name as title,name,level,auth')
                ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>$one['id'],'enginid'=>$enginid,'ismu'=>0])
                ->order('ismu ASC, sort ASC,id ASC')->select()->toArray();
            foreach ($children as &$item){
                $item['auth'] = explode(',', $item['auth']);

                $three = EnginMuModel::field('id,id as value,name as title,name,level,auth')
                    ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>$item['id'],'enginid'=>$enginid,'ismu'=>0])
                    ->order('ismu ASC, sort ASC,id ASC')->select()->toArray();
                foreach ($three as &$thvv){
                    $thvv['auth'] = explode(',', $thvv['auth']);
                    $thvv['children'] = [];
                }
                $item['children'] = $three;
            }
            $one['children'] = $children;
            $data['list'] = [$one];

//            $data['list'] = (new EnginService())->get_engin_mu_xmselect_xiang(0,$enginid);

            $engininfo = EnginModel::where(['id'=>$enginid])->find();
            $authArr = [];
            foreach (explode(',', $engininfo['jian_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            foreach (explode(',', $engininfo['she_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            foreach (explode(',', $engininfo['kan_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            foreach (explode(',', $engininfo['shi_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            foreach (explode(',', $engininfo['li_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            foreach (explode(',', $engininfo['yun_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            foreach (explode(',', $engininfo['gong_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            foreach (explode(',', $engininfo['zhi_unit']) as $dealid){
                $dealName = DealcomModel::where(['id'=>$dealid])->value('name');
                if($dealName){
                    $authArr[] = ['value'=>$dealid, 'name'=>$dealName];
                }
            }
            $data['authArr'] = $authArr;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_engin_mu(Request $request){
        $param = $request->post();
        $data = EnginMuModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

//        $existSon = EnginMuModel::where(['pid'=>$data['id'],'deleted_user'=>0])->find();
//        if($existSon){
//            return outputJson(4000, '该目录存在下级目录，无法删除');
//        }
//
//        $existBao = EnginBaoModel::where(['muid'=>$data['id'],'deleted_user'=>0,'status'=>1])->find();
//        if($existBao){
//            return outputJson(4000, '该目录存在上报文件，无法删除');
//        }
//
//        $existShen = EnginBaoModel::where(['muid'=>$data['id'],'deleted_user'=>0,'status'=>0])->find();
//        if($existShen){
//            return outputJson(4000, '该目录存在审核中的上报文件，无法删除');
//        }


        Db::startTrans();
        try {
            EnginMuModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            //删除子级
            EnginMuModel::where(Db::raw("find_in_set(".$data['id'].",`parents`)"))->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);

            (new EnginService())->set_engin_baonum($data['id']);

            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_mu', $data['id'], '文件夹');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin_mu(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginMuModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['data']['ismu_name'] = $data['data']['ismu'] > 0 ? '模板' : '文件夹';

        $dataSonArr = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$data['data']['enginid'],'deleted_user'=>0])
            ->where(Db::raw("find_in_set(".$data['data']['id'].",parents)"))->column('id');


        $size = 0;
        if($this->userinfo['token_roletype'] != 1){
            // 获取权限目录【包含子级】
            $myauthArr = EnginMuModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$data['data']['enginid'],'deleted_user'=>0])
                ->where(Db::raw("find_in_set(".$this->userinfo['dealid'].",auth)"))->column('id');

            foreach ($dataSonArr as $muid){
                if(in_array($muid, $myauthArr)){
                    $size += EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$data['data']['enginid']])
                        ->where(['muid'=>$muid,'deleted_user'=>0,'status'=>1])->sum('size');
                }else{
                    $size += EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$data['data']['enginid']])
                        ->where(['muid'=>$data['data']['id'],'dealid'=>$this->userinfo['dealid'],'deleted_user'=>0,'status'=>1])->sum('size');
                }
            }
        }else{
            $size += EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$data['data']['enginid']])
                ->where(['deleted_user'=>0,'status'=>1])
                ->where('muid','in', $dataSonArr)
                ->sum('size');
        }
        $data['data']['size'] = round($size/1024, 2);



        $parentsArr = explode(',', $data['data']['parents']);
        array_pop($parentsArr);
        $data['data']['muid_name'] = (new EnginService())->get_mu_quanname($parentsArr);
        $authArr = DealcomModel::where('id','in',$data['data']['auth'])->column('name');
        $data['data']['auth_name'] = implode('/', $authArr);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function down_engin_mu(Request $request){
        $enginid = $request->post('enginid', 0, 'int');
        $muid = $request->post('muid', 0, 'int');
        $engininfo = EnginModel::get_info_by_pk($enginid);
        if(!$engininfo){
            return outputJson(4000, lang('code_4000'));
        }
        $muinfo = EnginMuModel::get_info_by_pk($muid);
        if(!$muinfo){
            return outputJson(4000, lang('code_4000'));
        }


        $isFile = false;

        $file_dir = 'bao_zip/'.$this->userinfo['id'].'/';
        if(file_exists($file_dir)){
            $existAtt = scandir($file_dir);
            foreach ($existAtt as $value){
                if($value != '.' && $value != '..'){
                    unlink($file_dir.$value);
                }
            }
        }else{
            mkdir($file_dir, 0777);
        }
        $filename = $engininfo['name'].'.zip';
        $zip = new \ZipArchive();
        $res = $zip->open($file_dir.$filename, $zip::CREATE);
        if ($res === TRUE) {
            $arr = [['id'=>$muid,'name'=>'/'.$muinfo['name'].'/']];
            while (count($arr) > 0){
                $xinArr = [];
                foreach ($arr as $arrVal){
                    $arMuFiles = EnginBaoModel::where(['deleted_user'=>0,'enginid'=>$enginid,'status'=>1,'muid'=>$arrVal['id']])->select()->toArray();
                    foreach ($arMuFiles as $vvv){
                        if(file_exists($vvv['oripath'])){
                            $isFile = true;
                            $zip->addFile($vvv['oripath'], $arrVal['name'].$vvv['name']);
                        }
                    }

                    $arMuSon = EnginMuModel::field('id,name')->where(['deleted_user'=>0,'enginid'=>$enginid,'pid'=>$arrVal['id']])->select()->toArray();
                    foreach ($arMuSon as $sonVal){
                        $xinArr[] = ['id'=>$sonVal['id'],'name'=>$arrVal['name'].$sonVal['name'].'/'];
                    }
                }
                $arr = $xinArr;
            }
        }else{
            return outputJson(4000, '下载失败');
        }

        $zip->close();

        if(!$isFile){
            return outputJson(4000, '下载失败，该目录下暂无文件');
        }

        if(file_exists( iconv('utf-8', 'gbk', $file_dir.$filename))){
            return outputJson(2000,lang('code_2000'), $file_dir.$filename);
        }else{
            return outputJson(4000, '下载失败');
        }
    }
    public function paste_engin_mu(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $copyInfo = EnginMuModel::where(['id'=>$param['copyid']])->find();
            $pasteInfo = EnginMuModel::where(['id'=>$param['pasteid']])->find();
            if($copyInfo['pid'] < 1 || $copyInfo['ismu'] > 0 || $pasteInfo['ismu'] > 0){
                return outputJson(4000,lang('code_4000'));
            }

            Db::startTrans();
            try {
                $this->paset_chu_mu($param['copyid'], $param['pasteid'], $param['datatype']);


                // 复制：原上报文件【通过】，原样跟随过来，只统计粘贴的目录的上级目录数据  baonum不变  baoshennum有变化【单独处理】
                // 剪切：原上报文件【通过或者审核中】，原样跟随过来， 所以粘贴的文件目录的数量不变，只统计粘贴的目录的上级目录数据
                $copyInfo = EnginMuModel::where(['id'=>$param['copyid']])->find();
                $pasteInfo = EnginMuModel::where(['id'=>$param['pasteid']])->find();
                if($param['datatype'] == 'copy'){
                    $sonsArr = EnginMuModel::where(Db::raw("find_in_set(".$pasteInfo['id'].",`parents`)"))
                        ->where(['enginid'=>$pasteInfo['enginid'],'deleted_user'=>0])->column('id');
                    foreach ($sonsArr as $chuid){
                        (new EnginService())->set_engin_baonum($chuid);
                    }
                }else{
                    (new EnginService())->set_engin_baonum($copyInfo['pid']);
                    (new EnginService())->set_engin_baonum($pasteInfo['pid']);
                }


                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(4000,lang('code_4000'));
    }
    public function paset_chu_mu($copyid, $pasteid, $datatype){
        $copyInfo = EnginMuModel::where(['id'=>$copyid])->find();
        $pasteInfo = EnginMuModel::where(['id'=>$pasteid])->find();

        //复制文件夹
        $maxSort = EnginMuModel::where(['pid'=>$pasteInfo['id'],'deleted_user'=>0])->max('sort');
        $pasteArr = [
            'comid' => $pasteInfo['comid'],
            'enginid' => $pasteInfo['enginid'],
            'pid' => $pasteInfo['id'],
            'parents' => $pasteInfo['parents'],
            'level' => $pasteInfo['level']+1,
            'sort' => (int)$maxSort+1,
            'ismu' => $copyInfo['ismu'],
            'name' => (new EnginService())->check_engin_mu_name($copyInfo['name'], $pasteInfo['id'], $pasteInfo['enginid']),
            'ext' => $copyInfo['ext'],
            'size' => $copyInfo['size'],
            'oripath' => $copyInfo['oripath'],
            'encpath' => $copyInfo['encpath'],
            'baonum' => $copyInfo['baonum'],
            'baoshennum' => $copyInfo['baoshennum'],
            'created_user' => $this->userinfo['id'],
            'updated_user' => $this->userinfo['id'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        $pasteNewId = EnginMuModel::insertGetId($pasteArr);
        $pasteNewParents = $pasteArr['parents'].','.$pasteNewId;
        if($copyInfo['ismu'] > 0){
            $encpath =  encrypt($pasteNewId, 'E', Config::get('service.info_key'));
            EnginMuModel::where(['id'=>$pasteNewId])->update(['parents'=>$pasteNewParents,'encpath'=>$encpath]);
        }else{
            EnginMuModel::where(['id'=>$pasteNewId])->update(['parents'=>$pasteNewParents]);
        }


        if($datatype == 'copy'){
            //复制文件
            $fileArr = EnginBaoModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'status'=>1,'muid'=>$copyid])->select()->toArray();
            foreach ($fileArr as $fileItem){
                $baoarr = [];
                $baoarr['comid'] = $this->userinfo['comid'];
                $baoarr['status'] = $fileItem['status'];
                $baoarr['enginid'] = $fileItem['enginid'];
                $baoarr['dealid'] = $fileItem['dealid'];
                $baoarr['isadd'] = 1;
                $baoarr['muid'] = $pasteNewId;
                $baoarr['name'] = $fileItem['name'];
                $baoarr['ext'] = $fileItem['ext'];
                $baoarr['size'] = $fileItem['size'];
                $baoarr['oripath'] = $fileItem['oripath'];
                $baoarr['created_user'] = $this->userinfo['id'];
                $baoarr['updated_user'] = $this->userinfo['id'];
                $baoarr['created_at'] = date('Y-m-d H:i:s');
                $baoarr['updated_at'] = date('Y-m-d H:i:s');
                $bao_id = EnginBaoModel::insertGetId($baoarr);

                $encpath =  encrypt($bao_id, 'E', Config::get('service.info_key'));
                if(EnginBaoModel::where(['id'=>$bao_id])->update(['encpath'=>$encpath]) === false){
                    throw new Exception("上传失败");
                }

                (new OptService())->add_flow_log('复制', 'engin_bao', $bao_id);
                (new OptService())->add_log_list('复制', 'engin_bao', $bao_id, '上报文件');
            }
        }else{
            EnginMuModel::where(['id'=>$copyid])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            EnginBaoModel::where(['deleted_user'=>0,'muid'=>$copyid])->update(['muid'=>$pasteNewId]);
        }


        //处理子级
        $childrenArr = EnginMuModel::where(['pid'=>$copyid,'deleted_user'=>0])->select()->toArray();
        foreach ($childrenArr as $chilitem){
            $this->paset_chu_mu($chilitem['id'], $pasteNewId, $datatype);
        }
    }
    public function edit_engin_ban(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $oldInfo = EnginMuModel::where(['id'=>$param['id']])->find();

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                if($param['fileid']){
                    $fileinfo = FileModel::where(['id'=>$param['fileid']])->find();

                    $param['name'] = $param['name'].'.'.$fileinfo['ext'];
                    $param['ext'] = $fileinfo['ext'];
                    $param['size'] = $fileinfo['size'];
                    $param['oripath'] = $fileinfo['oripath'];
                    $param['encpath'] = encrypt($param['id'], 'E', Config::get('service.info_key'));
                }else{
                    $param['name'] = $param['name'].'.'.$oldInfo['ext'];
                }

                EnginMuModel::update($param);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_mu', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_mu', $param['id'], '文件资料库');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }

            $returninfo = EnginMuModel::where(['id'=>$param['id']])->find();
            $returninfo['parentsName'] = (new EnginService())->get_mu_quanname($returninfo['parents'], 1);
            return outputJson(2000,lang('code_2000'),['data'=>$returninfo]);
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginMuModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['data']['name'] = mb_substr($data['data']['name'], 0, mb_strlen($data['data']['name'])-4);

            $data['data']['pid_name'] = (new EnginService())->get_mu_quanname($data['data']['parents']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }




    public function add_engin_muban(Request $request)
    {
        $enginid = $request->param('enginid',0,'int');
        $muid = $request->param('muid',0,'int');
        $muidinfo = EnginMuModel::where(['id'=>$muid])->find();
        if($muidinfo['pid'] < 1){
            return outputJson(4000, '该文件夹无法上传模板,请重新上传');
        }

        $maxSort = EnginMuModel::where(['pid'=>$muid,'deleted_user'=>0])->max('sort');

        $files = request()->file('files');


        try{
            foreach ($files as $file){
                $fileInfo = $file->getInfo();
                $filesize = round($fileInfo['size']/1024,2);
                $info = $file->validate([
                    'size'=>Config::get('service.upload.size'),'ext'=>Config::get('service.upload.ext')
                ])->move($this->movePath);

                if($info){
                    $ins = [];
                    $ins['comid'] = $this->userinfo['comid'];
                    $ins['deptid'] = $this->userinfo['deptid'];
                    $ins['chanid'] = (new UserService())->get_user_chanid();
                    $ins['enginid'] = $muidinfo['enginid'];
                    $ins['pid'] = $muidinfo['id'];
                    $ins['parents'] = $muidinfo['parents'];
                    $ins['level'] = $muidinfo['level'] + 1;
                    $ins['sort'] = (int)$maxSort + 1;
                    $ins['ismu'] = 1;

                    $ins['name'] = $fileInfo['name'];
                    $ins['ext'] =  strtolower($info->getExtension());
                    $ins['size'] = $filesize;
                    $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                    $ins['created_user'] =  $this->userinfo['id'];
                    $ins['created_at'] =  date('Y-m-d H:i:s');
                    $ins['updated_at'] =  date('Y-m-d H:i:s');
                    $ins_id = EnginMuModel::insertGetId($ins);

                    $newParents = $muidinfo['parents'].','.$ins_id;
                    $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                    if(EnginMuModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath,'parents'=>$newParents]) === false){
                        throw new Exception("上传失败");
                    }
                }else{
                    throw new Exception("上传失败");
                }
            }
        }catch (\Exception $e){
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function shang_engin_mu(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $muinfo = EnginMuModel::where(['id'=>$param['id']])->find();
            $list = EnginMuModel::field('id,sort')
                ->where(['comid'=>$this->userinfo['comid'],'pid'=>$muinfo['pid'],'deleted_user'=>0])
                ->order('ismu ASC,sort ASC,id ASC')->select()->toArray();


            Db::startTrans();
            try {
                foreach ($list as $k=>$v){
                    $v['sort'] = $k+1;
                    EnginMuModel::where(['id'=>$v['id']])->update(['sort'=>$v['sort']]);
                }

                $updmuinfo = EnginMuModel::where(['id'=>$param['id']])->find();
                if($updmuinfo['sort'] != 1){
                    $shangmuinfo = EnginMuModel::where(['pid'=>$muinfo['pid'],'deleted_user'=>0,'sort'=>$updmuinfo['sort']-1])->find();
                    EnginMuModel::where(['id'=>$shangmuinfo['id']])->update(['sort'=>$updmuinfo['sort']]);
                    EnginMuModel::where(['id'=>$updmuinfo['id']])->update(['sort'=>$shangmuinfo['sort']]);
                }



                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function xia_engin_mu(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $muinfo = EnginMuModel::where(['id'=>$param['id']])->find();
            $list = EnginMuModel::field('id,sort')
                ->where(['comid'=>$this->userinfo['comid'],'pid'=>$muinfo['pid'],'deleted_user'=>0])
                ->order('ismu ASC,sort ASC,id ASC')->select()->toArray();


            Db::startTrans();
            try {
                foreach ($list as $k=>$v){
                    $v['sort'] = $k+1;
                    EnginMuModel::where(['id'=>$v['id']])->update(['sort'=>$v['sort']]);
                }

                $updmuinfo = EnginMuModel::where(['id'=>$param['id']])->find();
                if($updmuinfo['sort'] != count($list)){
                    $xiamuinfo = EnginMuModel::where(['pid'=>$muinfo['pid'],'deleted_user'=>0,'sort'=>$updmuinfo['sort']+1])->find();
                    EnginMuModel::where(['id'=>$xiamuinfo['id']])->update(['sort'=>$updmuinfo['sort']]);
                    EnginMuModel::where(['id'=>$updmuinfo['id']])->update(['sort'=>$xiamuinfo['sort']]);
                }



                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function wen_engin_mu(Request $request){
        $param = $request->post();

        $where[] = ['deleted_user','=', 0];
        $where[] = ['comid','=',$this->userinfo['comid']];
        $where[] = ['enginid','=',$param['enginid']];

        $list = [];

        $muidInfo = EnginMuModel::where(['id'=>$param['muid']])->find();
        if($muidInfo['ismu'] > 0){
            $bao = EnginBaoModel::where($where)->where(['muid'=>$muidInfo['id'],'status'=>1])->select()->toArray();
            $children = [];
            foreach ($bao as $baovv){
                $baoArr = [];
                $baoArr['type'] = 'bao';
                $baoArr['parentsName'] = (new EnginService())->get_mu_quanname($muidInfo['parents'], 1).'/'.$baovv['name'];
                $baoArr['id'] = $baovv['id'];
                $baoArr['pid'] = $muidInfo['id'];
                $baoArr['name'] = $baovv['name'];
                $baoArr['title'] = $baovv['name'];
                $baoArr['ext'] = $baovv['ext'];
                $baoArr['size'] = $baovv['size'];
                $baoArr['oripath'] = $baovv['oripath'];
                $baoArr['encpath'] = $baovv['encpath'];
                $children[] = $baoArr;
            }
            $muidInfo['children'] = $children;
            $muidInfo['type'] = 'ban';
            $muidInfo['parentsName'] = (new EnginService())->get_mu_quanname($muidInfo['parents'], 1);
            $muidInfo['title'] = '<span class="colorhong">【模板】</span>'.$muidInfo['name'];
            $list[] = $muidInfo;
        }else{
            $ban = EnginMuModel::where($where)->where(['pid'=>$param['muid'],'ismu'=>1])->select()->toArray();
            foreach ($ban as $banvv){
                $banArr = [];
                $banArr['type'] = 'ban';
                $banArr['id'] = $banvv['id'];
                $banArr['pid'] = $muidInfo['id'];
                $banArr['parentsName'] = (new EnginService())->get_mu_quanname($banvv['parents'], 1);
                $banArr['name'] = $banvv['name'];
                $banArr['title'] = '<span class="colorhong">【模板】</span>'.$banvv['name'];
                $banArr['ext'] = $banvv['ext'];
                $banArr['size'] = $banvv['size'];
                $banArr['oripath'] = $banvv['oripath'];
                $banArr['encpath'] = $banvv['encpath'];

                $children = [];
                $banbao = EnginBaoModel::where($where)->where(['muid'=>$banvv['id'],'status'=>1])->select()->toArray();
                foreach ($banbao as $bbvv){
                    $bbArr = [];
                    $bbArr['type'] = 'bao';
                    $bbArr['parentsName'] = (new EnginService())->get_mu_quanname($banvv['parents'], 1).'/'.$bbvv['name'];
                    $bbArr['id'] = $bbvv['id'];
                    $bbArr['pid'] = $banvv['id'];
                    $bbArr['name'] = $bbvv['name'];
                    $bbArr['title'] = $bbvv['name'];
                    $bbArr['ext'] = $bbvv['ext'];
                    $bbArr['size'] = $bbvv['size'];
                    $bbArr['oripath'] = $bbvv['oripath'];
                    $bbArr['encpath'] = $bbvv['encpath'];
                    $children[] = $bbArr;
                }
                $banArr['children'] = $children;
                $list[] = $banArr;
            }

            $bao = EnginBaoModel::where($where)->where(['muid'=>$param['muid'],'status'=>1])->select()->toArray();
            foreach ($bao as $baovv){
                $baoArr = [];
                $baoArr['type'] = 'bao';
                $baoArr['parentsName'] = (new EnginService())->get_mu_quanname($muidInfo['parents'], 1).'/'.$baovv['name'];
                $baoArr['id'] = $baovv['id'];
                $baoArr['pid'] = $muidInfo['id'];
                $baoArr['name'] = $baovv['name'];
                $baoArr['title'] = $baovv['name'];
                $baoArr['ext'] = $baovv['ext'];
                $baoArr['size'] = $baovv['size'];
                $baoArr['oripath'] = $baovv['oripath'];
                $baoArr['encpath'] = $baovv['encpath'];
                $list[] = $baoArr;
            }
        }




        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function wen_sea_engin_mu(Request $request){
        $param = $request->post();

        $where[] = ['sea.deleted_user','=', 0];
        $where[] = ['sea.comid','=',$this->userinfo['comid']];
        $where[] = ['sea.enginid','=',$param['enginid']];

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['sea.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['u.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $where[] = ['sea.created_at','between', explode(' - ', $param['created_at'])];
        }

        $list = [];

        $baninfo = EnginMuModel::alias('sea')
            ->field('sea.*')
            ->join('user u','u.id=sea.created_user')
            ->where($where)
            ->where(['sea.ismu'=>1])
            ->select()->toArray();
        foreach ($baninfo as $banVV){
            $banVV['type'] = 'ban';
            $banVV['title'] = '<span class="colorhong">【模板】</span>'.$banVV['name'];
            $banVV['parentsName'] = (new EnginService())->get_mu_quanname($banVV['parents'], 1);
            $banVV['children'] = [];
            if(!isset($list[$banVV['id']])){
                $list[$banVV['id']] = $banVV;
            }
        }


        $NoParBaoArr = [];
        $baoList = EnginBaoModel::alias('sea')
            ->field('sea.*')
            ->join('user u','u.id=sea.created_user')
            ->where($where)
            ->where(['sea.status'=>1])
            ->select()->toArray();
        foreach ($baoList as $baoVV){
            $ppinfo = EnginMuModel::where(['id'=>$baoVV['muid']])->find();
            $ppinfo['type'] = 'ban';
            $ppinfo['parentsName'] = (new EnginService())->get_mu_quanname($ppinfo['parents'], 1);
            $ppinfo['title'] = '<span class="colorhong">【模板】</span>'.$ppinfo['name'];

            $baoVV['parentsName'] = $ppinfo['parentsName'].'/'.$baoVV['name'];
            $baoVV['title'] = $baoVV['name'];
            $baoVV['type'] = 'bao';
            if($ppinfo['ismu'] > 0){
                if(isset($list[$ppinfo['id']])){
                    $list[$ppinfo['id']]['children'][] = $baoVV;
                }else{
                    $ppinfo['children'] = [$baoVV];
                    $list[$ppinfo['id']] = $ppinfo;
                }
            }else{
                $NoParBaoArr[] = $baoVV;
            }
        }


        $info = [];
        foreach ($list as $vv){
            $info[] = $vv;
        }
        foreach ($NoParBaoArr as $vvv){
            $info[] = $vvv;
        }

        $data['data'] = $info;
        return outputJson(2000,lang('code_2000'),$data);
    }


    public function list_engin_shi_count(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.areas','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['engintype']) && !empty($param['engintype'])){
            $where[] = ['e.engintype','=', $param['engintype']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['startdt']) && !empty($param['startdt'])){
            $where[] = ['e.startdt','between', explode(' - ', $param['startdt'])];
        }
        if(isset($param['enddt']) && !empty($param['enddt'])){
            $where[] = ['e.enddt','between', explode(' - ', $param['enddt'])];
        }

        $state = (new EnginService())->get_engin_state();
        $data['state'] = $state;
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_engintype'] = isset($param['engintype']) ? $param['engintype'] : '';


        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_shi', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['state_name'] = (new EnginService())->get_engin_state_name_tag($item['id'], $item['state']);

                $shi_unit_arr = explode(',', $item['shi_unit']);
                $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($item['id']);


                $whereArr = [];
                if($this->userinfo['token_roletype'] != 1){
                    if(!in_array($this->userinfo['dealid'], explode(',', $item['jian_unit']))){
                        $whereArr[] = ['dealid','=',$this->userinfo['dealid']];
                    }
                }

                $item['bao_ying'] = 0;
                $item['bao_shen1'] = 0;
                $item['bao_shen0'] = 0;
                $item['bao_no'] = 0;
                $item['bao_yi'] = 0;

                $item['bao_ying'] = count($shi_unit_arr) * count($yingDtArr);
                if($yingDtArr){
                    $item['bao_shen1'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0,'status'=>1])
                        ->where('dt','in',$yingDtArr)->group('dt')->where($whereArr)->count();
                    $item['bao_shen0'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0])
                        ->where('status','in',[0,2])->where($whereArr)->where('dt','in',$yingDtArr)->group('dt')->count();
                }else{
                    $item['bao_shen1'] = 0;
                    $item['bao_shen0'] = 0;
                }



                $item['bao_no'] = $item['bao_ying'] - $item['bao_shen1'];
                $item['bao_yi'] = $item['bao_shen1'] + $item['bao_shen0'];



//                if($this->userinfo['token_roletype'] == 1){
//                    $item['bao_ying'] = count($shi_unit_arr) * count($yingDtArr);
//                    $item['bao_shen1'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0,'status'=>1])
//                        ->where('dt','in',$yingDtArr)->group('dt')->count();
//                    $item['bao_shen0'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0])
//                        ->where('status','in',[0,2])
//                        ->where('dt','in',$yingDtArr)->group('dt')->count();
//
//                    $item['bao_no'] = $item['bao_ying'] - $item['bao_shen1'];
//                    $item['bao_yi'] = $item['bao_shen1'] + $item['bao_shen0'];
//                }else{
//                    if(in_array($this->userinfo['dealid'], $shi_unit_arr)){
//                        $item['bao_ying'] = count($yingDtArr);
//                    }
//
//                    $item['bao_shen1'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0,'status'=>1,'dealid'=>$this->userinfo['dealid']])
//                        ->where('dt','in',$yingDtArr)->group('dt')->count();
//                    $item['bao_shen0'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0,'dealid'=>$this->userinfo['dealid']])
//                        ->where('status','in',[0,2])
//                        ->where('dt','in',$yingDtArr)->group('dt')->count();
//
//                    $item['bao_no'] = $item['bao_ying'] - $item['bao_shen1'];
//                    $item['bao_yi'] = $item['bao_shen1'] + $item['bao_shen0'];
//                }



//                $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($item['id']);
//                if($yingDtArr){
//                    $item['bao_ying'] = count($yingDtArr);
//                    $item['bao_shen1'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0,'status'=>1])
//                        ->where('dt','in',$yingDtArr)->group('dt')->count();
//                    $item['bao_shen0'] = EnginShiModel::where(['enginid'=>$item['id'],'deleted_user'=>0])
//                        ->where('status','in',[0,2])
//                        ->where('dt','in',$yingDtArr)->group('dt')->count();
//                }
//                $item['bao_no'] = $item['bao_ying'] - $item['bao_shen1'];
//                $item['bao_yi'] = $item['bao_shen1'] + $item['bao_shen0'];

                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_shi(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['shi.deleted_user','=', 0];
        $where[] = ['shi.comid','=',$this->userinfo['comid']];
        $where[] = ['shi.enginid','=',$param['enginid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['user.realname|deal.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['dealid_name']) && !empty($param['dealid_name'])){
            $where[] = ['deal.name','like', '%'.$param['dealid_name'].'%'];
        }


        if(isset($param['dt']) && !empty($param['dt'])){
            $where[] = ['shi.dt','between', explode(' - ', $param['dt'])];
        }
        if(isset($param['status']) && $param['status'] != ''){
            if($param['status'] == 0){
                $where[] = ['shi.status','in', [0,2]];
            }else{
                $where[] = ['shi.status','=', $param['status']];
            }
        }



        if($this->userinfo['token_roletype'] != 1){
            $isJianer = (new EnginService())->check_user_is_jian($param['enginid']);
            if(!$isJianer){
                $where[] = ['shi.dealid','=',$this->userinfo['dealid']];
            }
        }


        $data['data'] = EnginShiModel::alias('shi')
            ->field('shi.*,user.realname as created_user_name,deal.name as dealid_name')
            ->leftJoin('dealcom deal','deal.id=shi.dealid')
            ->join('user user','user.id=shi.created_user')
            ->where($where)
            ->order('shi.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['token_roletype'] = $this->userinfo['token_roletype'];
                $item['enginname'] = EnginModel::where(['id'=>$item['enginid']])->value('name');
                $item['status_name'] = (new EnginService())->get_shi_status_name($item);


                $item['isshen'] = false;
                if($item['isjian'] > 0){
                    if($item['status'] == 0){
                        if( (new EnginService())->check_is_lishen($item['enginid']) ){
                            $item['isshen'] = true;
                        }
                    }elseif ($item['status'] == 2){
                        if( (new EnginService())->check_is_guanshen() ){
                            $item['isshen'] = true;
                        }
                    }
                }else{
                    if($item['status'] == 0){
                        if( (new EnginService())->check_is_guanshen() ){
                            $item['isshen'] = true;
                        }
                    }
                }


                return $item;
            })->toArray();


        $data['bao_no'] = 0;
        $shi_unit = EnginModel::where(['id'=>$param['enginid']])->value('shi_unit');
        if($shi_unit){
            $shi_unit_arr = explode(',', $shi_unit);
            $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($param['enginid']);
            foreach ($yingDtArr as $yydt){
                foreach ($shi_unit_arr as $shiunid){
                    $baoExist = EnginShiModel::where(['enginid'=>$param['enginid'],'deleted_user'=>0,'status'=>1])
                        ->where(['dt'=>$yydt,'dealid'=>$shiunid])->find();
                    if(!$baoExist){
                        $data['bao_no'] += 1;
                    }
                }
            }
        }



        $data['enginname'] = EnginModel::where(['id'=>$param['enginid']])->value('name');

        $data['butauth'] = (new MenuService())->get_butauth('engin_shi');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function lan_engin_shi(Request $request){
        $enginid = $request->post('enginid', 0, 'int');
        $date = $request->post('date','','string');
        $date = empty($date) ? date("Y-m-d") : $date;


        $engininfo = EnginModel::where(['id'=>$enginid])->find();

        $list = [];
        $dateArr = get_day($date, 3);
        $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($enginid);



        foreach ($dateArr as $vvv){
            $value = '';
            if(in_array($vvv['d'], $yingDtArr)){
                $shi = EnginShiModel::where(['enginid'=>$enginid,'deleted_user'=>0,'dt'=>$vvv['d'],'dealid'=>$this->userinfo['dealid']])->find();
                if($shi){
                    if($shi['status'] == 0 || $shi['status'] == 2){
                        $value = '<span class="curss curhuang" key="0" dataid="'.$shi['id'].'">'.$vvv['num'].'</span>';
                    }
                    if($shi['status'] == 1){
                        $value = '<span class="curss curlv" key="1" dataid="'.$shi['id'].'">'.$vvv['num'].'</span>';
                    }
                    if($shi['status'] == 9){
                        $value = '<span class="curss curzi" key="9" dataid="'.$shi['id'].'">'.$vvv['num'].'</span>';
                    }
                }else{
                    $value = '<span class="curss curhong" key="7">'.$vvv['num'].'</span>';
                }
            }else{
                $isRes = (new EnginService())->get_dt_is_kaijun($engininfo, $vvv['d']);
                if($isRes){
                    $value = '<span class="curss curhui" key="8">'.$vvv['num'].'</span>';
                }else{
                    $value = '<span class="curss curbai" key="8">'.$vvv['num'].'</span>';
                }
            }
            $list[$vvv['d']] = $value;
        }

        $data['date'] = $date;
        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function lanapp_engin_shi(Request $request){
        $enginid = $request->post('enginid', 0, 'int');
        $date = $request->post('date','','string');
        $date = empty($date) ? date("Y-m-d") : $date;


        $engininfo = EnginModel::where(['id'=>$enginid])->find();

        $list = [];
        $dateArr = get_day($date, 3);
        $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($enginid);



        foreach ($dateArr as $vvv){
            $info = ['status'=>-1, 'dataid'=>0];

            if(in_array($vvv['d'], $yingDtArr)){
                $shi = EnginShiModel::where(['enginid'=>$enginid,'deleted_user'=>0,'dt'=>$vvv['d'],'dealid'=>$this->userinfo['dealid']])->find();
                if($shi){
                    if($shi['status'] == 0 || $shi['status'] == 2){
                        $info = ['status'=>0, 'dataid'=>$shi['id']];
                    }
                    if($shi['status'] == 1){
                        $info = ['status'=>1, 'dataid'=>$shi['id']];
                    }
                    if($shi['status'] == 9){
                        $info = ['status'=>9, 'dataid'=>$shi['id']];
                    }
                }else{
                    $info = ['status'=>7, 'dataid'=>$shi['id']];
                }
            }else{
                $isRes = (new EnginService())->get_dt_is_kaijun($engininfo, $vvv['d']);
                if($isRes){
                    $info = ['status'=>8, 'dataid'=>0];
                }else{
                    $info = ['status'=>6, 'dataid'=>0];
                }
            }

            $info['statusclass'] = 'curstatus'.$info['status'];
            $info['date'] = $vvv['d'];
            $list[] = $info;
        }

        $data['data'] = $list;
        $data['enginname'] = $engininfo['name'];
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function add_engin_shi(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['gai'])){
                return outputJson(4000, '请输入施工概况');
            }

//            $exist = EnginShiModel::where(['enginid'=>$param['enginid'],'dt'=>$param['dt'],'deleted_user'=>0])->find();
//            if($exist){
//                if($exist['status'] == 0){
//                    return outputJson(4000, '该项目该日期已有施工日志正在审核中，无法提交');
//                }
//                if($exist['status'] == 1){
//                    return outputJson(4000, '该项目该日期已有施工日志审核通过，无法提交');
//                }
//            }

            $param['isjian'] = $this->cominfo['isjian'] > 0 ? 1 : 0;
            $param['dealid'] = $this->userinfo['dealid'];
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);
            $files = array_filter($param['files']);
            unset($param['files']);


            if(count($files) < 5){
                return outputJson(4000, '请上传至少5个附件信息');
            }


            Db::startTrans();
            try {
                $id = EnginShiModel::insertGetId($param);

                $enginInfo = EnginModel::where(['id'=>$param['enginid']])->find();
                if($this->cominfo['isjian'] > 0){
                    $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                }else{
                    $shenUserArr = (new EnginService())->get_guanuser();
                }
                foreach($shenUserArr as $uid){
                    (new WorkerService())->add_worker($uid, '施工日志',$enginInfo['name'], $id, 'engin_shi');
                }


                (new OptService())->relation_file($files,'engin_shi',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_shi', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_shi', $id, '施工日志');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->param('enginid',0,'int');
            $dt = $request->param('dt',0,'string');

            $enginInfo = EnginModel::where(['id'=>$enginid])->find();

            $data['enginname'] = $enginInfo['name'];
            $data['shi_unit_name'] = DealcomModel::get_name_by_ids($enginInfo['shi_unit']);
            $data['dt'] = $dt;
            $data['title'] = '施工日志('.$dt.')';
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin_shi(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['gai'])){
                return outputJson(4000, '请输入施工概况');
            }

            $oldInfo = EnginShiModel::where(['id'=>$param['id']])->find();

//            $exist = EnginShiModel::where(['enginid'=>$oldInfo['enginid'],'dt'=>$param['dt'],'deleted_user'=>0])->where('id','neq',$param['id'])->find();
//            if($exist){
//                if($exist['status'] == 0){
//                    return outputJson(4000, '该项目该日期已有施工日志正在审核中，无法提交');
//                }
//                if($exist['status'] == 1){
//                    return outputJson(4000, '该项目该日期已有施工日志审核通过，无法提交');
//                }
//            }

            $param['isjian'] = $this->cominfo['isjian'] > 0 ? 1 : 0;
            $param['status'] = 0;
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);
            $files = array_filter($param['files']);
            unset($param['files']);

            if(count($files) < 1){
                return outputJson(4000, '请上传至少5个附件信息');
            }

            Db::startTrans();
            try {
                EnginShiModel::update($param);

                $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                if($this->cominfo['isjian'] > 0){
                    $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                }else{
                    $shenUserArr = (new EnginService())->get_guanuser();
                }
                foreach($shenUserArr as $uid){
                    (new WorkerService())->add_worker($uid, '施工日志',$enginInfo['name'], $oldInfo['id'], 'engin_shi');
                }


                (new OptService())->relation_file($files,'engin_shi',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_shi', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_shi', $param['id'], '施工日志');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginShiModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $enginInfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
            $data['data']['enginname'] = $enginInfo['name'];
            $data['data']['shi_unit_name'] = DealcomModel::get_name_by_ids($enginInfo['shi_unit']);
            $data['files'] = (new OptService())->get_file('engin_shi', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_engin_shi(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginShiModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }
        $data['data']['status_name'] = (new EnginService())->get_shi_status_name($data['data']);
        $enginInfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
        $data['data']['enginname'] = $enginInfo['name'];
        $data['data']['shi_unit_name'] = DealcomModel::get_name_by_ids($enginInfo['shi_unit']);
        $data['files'] = (new OptService())->get_file('engin_shi', $data['data']['id']);

        $data['data']['created_user_name'] = UserModel::where(['id'=>$data['data']['created_user']])->value('realname');
        $data['data']['dealid_name'] = DealcomModel::where(['id'=>$data['data']['dealid']])->value('name');

        $isshen = false;
        if($data['data']['isjian'] > 0){
            if($data['data']['status'] == 0){
                if( (new EnginService())->check_is_lishen($data['data']['enginid']) ){
                    $isshen = true;
                }
            }elseif ($data['data']['status'] == 2){
                if( (new EnginService())->check_is_guanshen() ){
                    $isshen = true;
                }else{
                    if( (new EnginService())->check_is_jianshen($data['data']['enginid']) ){
                        $isshen = true;
                    }
                }
            }
        }else{
            if($data['data']['status'] == 0){
                if( (new EnginService())->check_is_guanshen() ){
                    $isshen = true;
                }else{
                    if( (new EnginService())->check_is_jianshen($data['data']['enginid']) ){
                        $isshen = true;
                    }
                }
            }
        }
        $data['isshen'] = $isshen;

        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_engin_shi(Request $request){
        $param = $request->post();
        $data = EnginShiModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            EnginShiModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);

            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_shi', $data['id'], '施工日志');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function shen_engin_shi(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $oldInfo = EnginShiModel::where(['id'=>$param['id']])->find();
            if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                return outputJson(4000, lang('code_4000'));
            }

            $statusName = '';
            if($oldInfo['isjian'] > 0){
                if($oldInfo['status'] == 0){
                    if( !(new EnginService())->check_is_lishen($oldInfo['enginid']) ){
                        return outputJson(4000, lang('code_4000'));
                    }
                    $statusName = $param['status'] == 1 ? '通过[监理]' : '驳回[监理]';

                    if($param['status'] == 1){
                        $param['status'] = 2;
                    }
                }elseif ($oldInfo['status'] == 2){
                    if( !(new EnginService())->check_is_guanshen() ){
                        if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                            return outputJson(4000, lang('code_4000'));
                        }
                    }
                    $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
                }else{
                    return outputJson(4000, lang('code_4000'));
                }
            }else{
                if ($oldInfo['status'] == 0){
                    if( !(new EnginService())->check_is_guanshen() ){
                        if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                            return outputJson(4000, lang('code_4000'));
                        }
                    }
                    $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
                }else{
                    return outputJson(4000, lang('code_4000'));
                }
            }

            Db::startTrans();
            try {
                EnginShiModel::where(['id'=>$param['id']])->update(['status'=>$param['status']]);

                if($param['status'] == 2){
                    $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                    $shenUserArr = (new EnginService())->get_guanuser();
                    foreach($shenUserArr as $uid){
                        (new WorkerService())->add_worker($uid, '施工日志',$enginInfo['name'], $oldInfo['id'], 'engin_shi');
                    }
                }


                (new OptService())->add_flow_log('审核', 'engin_shi', $param['id'], $statusName, $param['explain'], $param['files']);
                (new OptService())->add_log_list('审核', 'engin_shi', $param['id'], '施工日志');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function mulshen_engin_shi(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $ids = $request->post('ids','string','');

            Db::startTrans();
            try {

                $oldArr = EnginShiModel::where('id','in',$ids)->select()->toArray();
                foreach ($oldArr as $oldInfo){
                    if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                        continue;
                    }

                    $statusName = '';
                    $status = $param['status'];
                    if($oldInfo['isjian'] > 0){
                        if($oldInfo['status'] == 0){
                            if( !(new EnginService())->check_is_lishen($oldInfo['enginid']) ){
                                continue;
                            }
                            $statusName = $status == 1 ? '通过[监理]' : '驳回[监理]';

                            if($status == 1){
                                $status = 2;
                            }
                        }elseif ($oldInfo['status'] == 2){
                            if( !(new EnginService())->check_is_guanshen() ){
                                if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                                    continue;
                                }
                            }
                            $statusName = $status == 1 ? '通过[管理员]' : '驳回[管理员]';
                        }else{
                            continue;
                        }
                    }else{
                        if ($oldInfo['status'] == 0){
                            if( !(new EnginService())->check_is_guanshen() ){
                                if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                                    continue;
                                }
                            }
                            $statusName = $status == 1 ? '通过[管理员]' : '驳回[管理员]';
                        }else{
                            continue;
                        }
                    }


                    EnginShiModel::where(['id'=>$oldInfo['id']])->update(['status'=>$status]);

                    if($status == 2){
                        $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                        $shenUserArr = (new EnginService())->get_guanuser();
                        foreach($shenUserArr as $uid){
                            (new WorkerService())->add_worker($uid, '施工日志',$enginInfo['name'], $oldInfo['id'], 'engin_shi');
                        }
                    }


                    (new OptService())->add_flow_log('审核', 'engin_shi', $oldInfo['id'], $statusName, $param['explain']);
                    (new OptService())->add_log_list('审核', 'engin_shi', $oldInfo['id'], '施工日志');
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }



    public function list_engin_jian_count(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.areas','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['engintype']) && !empty($param['engintype'])){
            $where[] = ['e.engintype','=', $param['engintype']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['startdt']) && !empty($param['startdt'])){
            $where[] = ['e.startdt','between', explode(' - ', $param['startdt'])];
        }
        if(isset($param['enddt']) && !empty($param['enddt'])){
            $where[] = ['e.enddt','between', explode(' - ', $param['enddt'])];
        }

        $state = (new EnginService())->get_engin_state();
        $data['state'] = $state;
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_engintype'] = isset($param['engintype']) ? $param['engintype'] : '';


        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_jian', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['state_name'] = (new EnginService())->get_engin_state_name_tag($item['id'], $item['state']);

                $whereArr = [];
                if($this->userinfo['token_roletype'] != 1){
                    if(!in_array($this->userinfo['dealid'], explode(',', $item['jian_unit']))){
                        $whereArr[] = ['dealid','=',$this->userinfo['dealid']];
                    }
                }

                $item['bao_ying'] = 0;
                $item['bao_shen1'] = 0;
                $item['bao_shen0'] = 0;
                $item['bao_no'] = 0;
                $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($item['id']);
                if($yingDtArr){
                    $item['bao_ying'] = count($yingDtArr);
                    $item['bao_shen1'] = EnginJianModel::where(['enginid'=>$item['id'],'deleted_user'=>0,'status'=>1])
                        ->where('dt','in',$yingDtArr)->group('dt')->where($whereArr)->count();
                    $item['bao_shen0'] = EnginJianModel::where(['enginid'=>$item['id'],'deleted_user'=>0,'status'=>0])
                        ->where('dt','in',$yingDtArr)->group('dt')->where($whereArr)->count();
                }
                $item['bao_no'] = $item['bao_ying'] - $item['bao_shen1'];
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_jian(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['jian.deleted_user','=', 0];
        $where[] = ['jian.comid','=',$this->userinfo['comid']];
        $where[] = ['jian.enginid','=',$param['enginid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['user.realname','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['dt']) && !empty($param['dt'])){
            $where[] = ['jian.dt','between', explode(' - ', $param['dt'])];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['jian.status','=', $param['status']];
        }

        if($this->userinfo['token_roletype'] != 1){
            $isJianer = (new EnginService())->check_user_is_jian($param['enginid']);
            if(!$isJianer){
                $where[] = ['jian.dealid','=',$this->userinfo['dealid']];
            }
        }

        $data['data'] = EnginJianModel::alias('jian')
            ->field('jian.*,user.realname as created_user_name')
            ->join('user user','user.id=jian.created_user')
            ->where($where)
            ->order('jian.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['token_roletype'] = $this->userinfo['token_roletype'];
                $item['enginname'] = EnginModel::where(['id'=>$item['enginid']])->value('name');
                $item['status_name'] = (new EnginService())->get_jian_status_name($item);
                $item['dealid_name'] = DealcomModel::where(['id'=>$item['dealid']])->value('name');

                $item['isshen'] = false;
                if($item['status'] == 0){
                    if( (new EnginService())->check_is_guanshen() ){
                        $item['isshen'] = true;
                    }
                }

                return $item;
            })->toArray();


        $bao_ying = 0;
        $bao_shen1 = 0;
        $data['bao_no'] = 0;
        $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($param['enginid']);
        if($yingDtArr){
            $bao_ying = count($yingDtArr);
            $bao_shen1 = EnginJianModel::where(['enginid'=>$param['enginid'],'deleted_user'=>0,'status'=>1])
                ->where('dt','in',$yingDtArr)->group('dt')->count();
        }
        $data['bao_no'] = $bao_ying - $bao_shen1;

        $data['enginname'] = EnginModel::where(['id'=>$param['enginid']])->value('name');

        $data['butauth'] = (new MenuService())->get_butauth('engin_jian');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function lan_engin_jian(Request $request){
        $enginid = $request->post('enginid', 0, 'int');
        $date = $request->post('date','','string');
        $date = empty($date) ? date("Y-m-d") : $date;

        $engininfo = EnginModel::where(['id'=>$enginid])->find();


        $list = [];
        $dateArr = get_day($date, 3);
        $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($enginid);



        foreach ($dateArr as $vvv){
            $value = '';
            if(in_array($vvv['d'], $yingDtArr)){
                $jian = EnginJianModel::where(['enginid'=>$enginid,'deleted_user'=>0,'dt'=>$vvv['d']])->find();
                if($jian){
                    if($jian['status'] == 0){
                        $value = '<span class="curss curhuang" key="0" dataid="'.$jian['id'].'">'.$vvv['num'].'</span>';
                    }
                    if($jian['status'] == 1){
                        $value = '<span class="curss curlv" key="1" dataid="'.$jian['id'].'">'.$vvv['num'].'</span>';
                    }
                    if($jian['status'] == 9){
                        $value = '<span class="curss curzi" key="9" dataid="'.$jian['id'].'">'.$vvv['num'].'</span>';
                    }
                }else{
                    $value = '<span class="curss curhong" key="7">'.$vvv['num'].'</span>';
                }
            }else{
                $isRes = (new EnginService())->get_dt_is_kaijun($engininfo, $vvv['d']);
                if($isRes){
                    $value = '<span class="curss curhui" key="8">'.$vvv['num'].'</span>';
                }else{
                    $value = '<span class="curss curbai" key="8">'.$vvv['num'].'</span>';
                }
            }
            $list[$vvv['d']] = $value;
        }

        $data['date'] = $date;
        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function lanapp_engin_jian(Request $request){
        $enginid = $request->post('enginid', 0, 'int');
        $date = $request->post('date','','string');
        $date = empty($date) ? date("Y-m-d") : $date;


        $engininfo = EnginModel::where(['id'=>$enginid])->find();

        $list = [];
        $dateArr = get_day($date, 3);
        $yingDtArr = (new EnginService())->get_engin_shi_yinginfo($enginid);



        foreach ($dateArr as $vvv){
            $info = ['status'=>-1, 'dataid'=>0];

            if(in_array($vvv['d'], $yingDtArr)){
                $jian = EnginJianModel::where(['enginid'=>$enginid,'deleted_user'=>0,'dt'=>$vvv['d']])->find();
                if($jian){
                    if($jian['status'] == 0 || $jian['status'] == 2){
                        $info = ['status'=>0, 'dataid'=>$jian['id']];
                    }
                    if($jian['status'] == 1){
                        $info = ['status'=>1, 'dataid'=>$jian['id']];
                    }
                    if($jian['status'] == 9){
                        $info = ['status'=>9, 'dataid'=>$jian['id']];
                    }
                }else{
                    $info = ['status'=>7, 'dataid'=>$jian['id']];
                }
            }else{
                $isRes = (new EnginService())->get_dt_is_kaijun($engininfo, $vvv['d']);
                if($isRes){
                    $info = ['status'=>8, 'dataid'=>0];
                }else{
                    $info = ['status'=>6, 'dataid'=>0];
                }
            }

            $info['statusclass'] = 'curstatus'.$info['status'];
            $info['date'] = $vvv['d'];
            $list[] = $info;
        }

        $data['data'] = $list;
        $data['enginname'] = $engininfo['name'];
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function add_engin_jian(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['gai'])){
                return outputJson(4000, '请输入监理概况');
            }

            $exist = EnginJianModel::where(['enginid'=>$param['enginid'],'dt'=>$param['dt'],'deleted_user'=>0])->find();
            if($exist){
                if($exist['status'] == 0){
                    return outputJson(4000, '该项目该日期已有监理日志正在审核中，无法提交');
                }
                if($exist['status'] == 1){
                    return outputJson(4000, '该项目该日期已有监理日志审核通过，无法提交');
                }
            }

            $param['dealid'] = $this->userinfo['dealid'];
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);
            $files = array_filter($param['files']);
            unset($param['files']);

            if(count($files) < 1){
                return outputJson(4000, '请上传附件信息');
            }

            Db::startTrans();
            try {
                $id = EnginJianModel::insertGetId($param);


                $enginInfo = EnginModel::where(['id'=>$param['enginid']])->find();
                $shenUserArr = (new EnginService())->get_guanuser();
                foreach($shenUserArr as $uid){
                    (new WorkerService())->add_worker($uid, '监理日志',$enginInfo['name'], $id, 'engin_jian');
                }

                (new OptService())->relation_file($files,'engin_jian',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_jian', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_jian', $id, '监理日志');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->param('enginid',0,'int');
            $dt = $request->param('dt',0,'string');

            $enginInfo = EnginModel::where(['id'=>$enginid])->find();

            $data['enginname'] = $enginInfo['name'];
            $data['li_unit_name'] = DealcomModel::get_name_by_ids($enginInfo['li_unit']);
            $data['dt'] = $dt;
            $data['title'] = '监理日志('.$dt.')';
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin_jian(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['gai'])){
                return outputJson(4000, '请输入监理概况');
            }

            $oldInfo = EnginJianModel::where(['id'=>$param['id']])->find();

            $exist = EnginJianModel::where(['enginid'=>$oldInfo['enginid'],'dt'=>$param['dt'],'deleted_user'=>0])->where('id','neq',$param['id'])->find();
            if($exist){
                if($exist['status'] == 0){
                    return outputJson(4000, '该项目该日期已有监理日志正在审核中，无法提交');
                }
                if($exist['status'] == 1){
                    return outputJson(4000, '该项目该日期已有监理日志审核通过，无法提交');
                }
            }

            $param['status'] = 0;
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);
            $files = array_filter($param['files']);
            unset($param['files']);

            if(count($files) < 1){
                return outputJson(4000, '请上传附件信息');
            }

            Db::startTrans();
            try {
                EnginJianModel::update($param);

                $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                $shenUserArr = (new EnginService())->get_guanuser();
                foreach($shenUserArr as $uid){
                    (new WorkerService())->add_worker($uid, '监理日志',$enginInfo['name'], $param['id'], 'engin_jian');
                }

                (new OptService())->relation_file($files,'engin_jian',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_jian', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_jian', $param['id'], '监理日志');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginJianModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $enginInfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
            $data['data']['enginname'] = $enginInfo['name'];
            $data['data']['li_unit_name'] = DealcomModel::get_name_by_ids($enginInfo['li_unit']);
            $data['files'] = (new OptService())->get_file('engin_jian', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_engin_jian(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginJianModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }
        $data['data']['status_name'] = (new EnginService())->get_jian_status_name($data['data']);
        $enginInfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
        $data['data']['enginname'] = $enginInfo['name'];
        $data['data']['li_unit_name'] = DealcomModel::get_name_by_ids($enginInfo['li_unit']);
        $data['files'] = (new OptService())->get_file('engin_jian', $data['data']['id']);

        $data['data']['created_user_name'] = UserModel::where(['id'=>$data['data']['created_user']])->value('realname');
        $data['data']['dealid_name'] = DealcomModel::where(['id'=>$data['data']['dealid']])->value('name');

        $isshen = false;
        if($data['data']['status'] == 0){
            if( (new EnginService())->check_is_guanshen() ){
                $isshen = true;
            }else{
                if( (new EnginService())->check_is_jianshen($data['data']['enginid']) ){
                    $isshen = true;
                }
            }
        }
        $data['isshen'] = $isshen;
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_engin_jian(Request $request){
        $param = $request->post();
        $data = EnginJianModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            EnginJianModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);

            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_jian', $data['id'], '监理日志');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function shen_engin_jian(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $oldInfo = EnginJianModel::where(['id'=>$param['id']])->find();
            if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                return outputJson(4000, lang('code_4000'));
            }

            $statusName = '';
            if($oldInfo['status'] == 0){
                if( !(new EnginService())->check_is_guanshen() ){
                    if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                        return outputJson(4000, lang('code_4000'));
                    }
                }
                $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
            }else{
                return outputJson(4000, lang('code_4000'));
            }

            Db::startTrans();
            try {
                EnginJianModel::where(['id'=>$param['id']])->update(['status'=>$param['status']]);

                (new OptService())->add_flow_log('审核', 'engin_jian', $param['id'], $statusName, $param['explain'], $param['files']);
                (new OptService())->add_log_list('审核', 'engin_jian', $param['id'], '监理日志');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function mulshen_engin_jian(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $ids = $request->post('ids','string','');

            Db::startTrans();
            try {

                $oldArr = EnginJianModel::where('id','in',$ids)->select()->toArray();
                foreach ($oldArr as $oldInfo){
                    if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                        continue;
                    }

                    $statusName = '';
                    if($oldInfo['status'] == 0){
                        if( !(new EnginService())->check_is_guanshen() ){
                            if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                                continue;
                            }
                        }
                        $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
                    }else{
                        continue;
                    }

                    EnginJianModel::where(['id'=>$oldInfo['id']])->update(['status'=>$param['status']]);

                    (new OptService())->add_flow_log('审核', 'engin_jian', $oldInfo['id'], $statusName, $param['explain']);
                    (new OptService())->add_log_list('审核', 'engin_jian', $oldInfo['id'], '监理日志');
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }



    public function list_engin_yue_count(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.areas','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['engintype']) && !empty($param['engintype'])){
            $where[] = ['e.engintype','=', $param['engintype']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['startdt']) && !empty($param['startdt'])){
            $where[] = ['e.startdt','between', explode(' - ', $param['startdt'])];
        }
        if(isset($param['enddt']) && !empty($param['enddt'])){
            $where[] = ['e.enddt','between', explode(' - ', $param['enddt'])];
        }

        $state = (new EnginService())->get_engin_state();
        $data['state'] = $state;
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_engintype'] = isset($param['engintype']) ? $param['engintype'] : '';


        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_yue', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['state_name'] = (new EnginService())->get_engin_state_name_tag($item['id'], $item['state']);
                $item['state_nameapp'] = (new EnginService())->get_engin_state_name($item['id'], $item['state']);

                $item['chanfee'] = (new EnginService())->get_engin_yue_chanfee($item['id']);
                $item['chanrate'] = 0;
                if($item['hemoney'] != 0){
                    $item['chanrate'] = round($item['chanfee'] / $item['hemoney'] * 100, 2);
                }

                $item['lastMonth'] = '';
                $lastYue = EnginYueModel::where(['enginid'=>$item['id'],'status'=>1])
                    ->where('month','<=', date("Y-m"))
                    ->order('month DESC')->find();
                if($lastYue){
                    $item['lastMonth'] = $lastYue['month'];
                }

                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_yue(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['yue.deleted_user','=', 0];
        $where[] = ['yue.comid','=',$this->userinfo['comid']];
        $where[] = ['yue.enginid','=',$param['enginid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['user.realname','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['month']) && !empty($param['month'])){
            $where[] = ['yue.month','between', explode(' - ', $param['month'])];
        }
        if(isset($param['status']) && $param['status'] != ''){
            if($param['status'] == 0){
                $where[] = ['yue.status','in', [0,2]];
            }else{
                $where[] = ['yue.status','=', $param['status']];
            }
        }

        if($this->userinfo['token_roletype'] != 1){
            $isJianer = (new EnginService())->check_user_is_jian($param['enginid']);
            if(!$isJianer){
                $where[] = ['yue.dealid','=',$this->userinfo['dealid']];
            }
        }

        $data['data'] = EnginYueModel::alias('yue')
            ->field('yue.*,user.realname as created_user_name')
            ->join('user user','user.id=yue.created_user')
            ->where($where)
            ->order('yue.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['token_roletype'] = $this->userinfo['token_roletype'];
                $item['enginname'] = EnginModel::where(['id'=>$item['enginid']])->value('name');
                $item['status_name'] = (new EnginService())->get_yue_status_name($item);
                $item['dealid_name'] = DealcomModel::where(['id'=>$item['dealid']])->value('name');

                $item['isshen'] = false;
                if($item['isjian'] > 0){
                    if($item['status'] == 0){
                        if( (new EnginService())->check_is_lishen($item['enginid']) ){
                            $item['isshen'] = true;
                        }
                    }elseif ($item['status'] == 2){
                        if( (new EnginService())->check_is_guanshen() ){
                            $item['isshen'] = true;
                        }
                    }
                }else{
                    if($item['status'] == 0){
                        if( (new EnginService())->check_is_guanshen() ){
                            $item['isshen'] = true;
                        }
                    }
                }

                return $item;
            })->toArray();
        $data['enginname'] = EnginModel::where(['id'=>$param['enginid']])->value('name');
        $data['butauth'] = (new MenuService())->get_butauth('engin_yue');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_yue(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['month'])){
                return outputJson(4000, '请选择填报月份');
            }
            if($param['chanfee'] == ''){
                return outputJson(4000, '请输入本月完成产值');
            }

            $param['isjian'] = $this->cominfo['isjian'] > 0 ? 1 : 0;
            $param['dealid'] = $this->userinfo['dealid'];
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);
            $files = array_filter($param['files']);
            unset($param['files']);

            if(count($files) < 1){
                return outputJson(4000, '请上传附件信息');
            }

            Db::startTrans();
            try {
                $id = EnginYueModel::insertGetId($param);

                $enginInfo = EnginModel::where(['id'=>$param['enginid']])->find();
                if($this->cominfo['isjian'] > 0){
                    $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                }else{
                    $shenUserArr = (new EnginService())->get_guanuser();
                }
                foreach($shenUserArr as $uid){
                    (new WorkerService())->add_worker($uid, '进度月报',$enginInfo['name'], $id, 'engin_yue');
                }

                (new OptService())->relation_file($files,'engin_yue',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_yue', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_yue', $id, '进度月报');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->param('enginid',0,'int');
            $dt = $request->param('dt',0,'string');

            $enginInfo = EnginModel::where(['id'=>$enginid])->find();

            $data['enginname'] = $enginInfo['name'];
            $data['hemoney'] = $enginInfo['hemoney'];

            $data['chanfee_qian'] = (new EnginService())->get_engin_yue_chanfee($enginInfo['id']);
            $data['chanrate_qian'] = 0;
            if($data['hemoney'] != 0){
                $data['chanrate_qian'] = round($data['chanfee_qian'] / $data['hemoney'] * 100, 2);
            }

            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin_yue(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['month'])){
                return outputJson(4000, '请选择填报月份');
            }
            if($param['chanfee'] == ''){
                return outputJson(4000, '请输入本月完成产值');
            }

            $oldInfo = EnginYueModel::where(['id'=>$param['id']])->find();

            $param['isjian'] = $this->cominfo['isjian'] > 0 ? 1 : 0;
            $param['status'] = 0;
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);
            $files = array_filter($param['files']);
            unset($param['files']);

            if(count($files) < 1){
                return outputJson(4000, '请上传附件信息');
            }

            Db::startTrans();
            try {
                EnginYueModel::update($param);

                $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                if($this->cominfo['isjian'] > 0){
                    $shenUserArr = UserModel::where(['deleted_user'=>0])->where('dealid','in',$enginInfo['li_unit'])->column('id');
                }else{
                    $shenUserArr = (new EnginService())->get_guanuser();
                }
                foreach($shenUserArr as $uid){
                    (new WorkerService())->add_worker($uid, '进度月报',$enginInfo['name'], $oldInfo['id'], 'engin_yue');
                }

                (new OptService())->relation_file($files,'engin_yue',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_yue', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_yue', $param['id'], '进度月报');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginYueModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $enginInfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
            $data['data']['enginname'] = $enginInfo['name'];
            $data['data']['hemoney'] = $enginInfo['hemoney'];
            $data['data']['chanfee_qian'] = EnginYueModel::where(['enginid'=>$enginInfo['id'],'status'=>1,'deleted_user'=>0])->where('id','neq',$data['data']['id'])->sum('chanfee');
            $data['data']['chanrate_qian'] = 0;
            if($enginInfo['hemoney'] != 0){
                $data['data']['chanrate_qian'] = round($data['data']['chanfee_qian'] / $enginInfo['hemoney'] * 100, 2);
            }


            $data['data']['chanfee_lei'] = round($data['data']['chanfee_qian'] + $data['data']['chanfee'], 2);
            $data['data']['chanrate_lei'] = 0;
            if($enginInfo['hemoney'] != 0){
                $data['data']['chanrate_lei'] = round(($data['data']['chanfee_qian'] + $data['data']['chanfee']) / $enginInfo['hemoney'] * 100, 2);
            }
            $data['files'] = (new OptService())->get_file('engin_yue', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_engin_yue(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginYueModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }
        $data['data']['status_name'] = (new EnginService())->get_yue_status_name($data['data']);
        $enginInfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
        $data['data']['enginname'] = $enginInfo['name'];
        $data['data']['hemoney'] = $enginInfo['hemoney'];
        $data['data']['chanfee_lei'] = (new EnginService())->get_engin_yue_chanfee($enginInfo['id']);
        $data['data']['chanrate_lei'] = 0;
        if($enginInfo['hemoney'] != 0){
            $data['data']['chanrate_lei'] = round($data['data']['chanfee_lei'] / $enginInfo['hemoney'] * 100, 2);
        }
        $data['files'] = (new OptService())->get_file('engin_yue', $data['data']['id']);

        $data['data']['created_user_name'] = UserModel::where(['id'=>$data['data']['created_user']])->value('realname');
        $data['data']['dealid_name'] = DealcomModel::where(['id'=>$data['data']['dealid']])->value('name');


        $isshen = false;
        if($data['data']['isjian'] > 0){
            if($data['data']['status'] == 0){
                if( (new EnginService())->check_is_lishen($data['data']['enginid']) ){
                    $isshen = true;
                }
            }elseif ($data['data']['status'] == 2){
                if( (new EnginService())->check_is_guanshen() ){
                    $isshen = true;
                }else{
                    if( (new EnginService())->check_is_jianshen($data['data']['enginid']) ){
                        $isshen = true;
                    }
                }
            }
        }else{
            if($data['data']['status'] == 0){
                if( (new EnginService())->check_is_guanshen() ){
                    $isshen = true;
                }else{
                    if( (new EnginService())->check_is_jianshen($data['data']['enginid']) ){
                        $isshen = true;
                    }
                }
            }
        }
        $data['isshen'] = $isshen;
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_engin_yue(Request $request){
        $param = $request->post();
        $data = EnginYueModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            EnginYueModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);

            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_yue', $data['id'], '进度月报');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function shen_engin_yue(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $oldInfo = EnginYueModel::where(['id'=>$param['id']])->find();
            if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                return outputJson(4000, lang('code_4000'));
            }

            $statusName = '';
            if($oldInfo['isjian'] > 0){
                if($oldInfo['status'] == 0){
                    if( !(new EnginService())->check_is_lishen($oldInfo['enginid']) ){
                        return outputJson(4000, lang('code_4000'));
                    }
                    $statusName = $param['status'] == 1 ? '通过[监理]' : '驳回[监理]';

                    if($param['status'] == 1){
                        $param['status'] = 2;
                    }
                }elseif ($oldInfo['status'] == 2){
                    if( !(new EnginService())->check_is_guanshen() ){
                        if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                            return outputJson(4000, lang('code_4000'));
                        }
                    }
                    $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
                }else{
                    return outputJson(4000, lang('code_4000'));
                }
            }else{
                if ($oldInfo['status'] == 0){
                    if( !(new EnginService())->check_is_guanshen() ){
                        if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                            return outputJson(4000, lang('code_4000'));
                        }
                    }
                    $statusName = $param['status'] == 1 ? '通过[管理员]' : '驳回[管理员]';
                }else{
                    return outputJson(4000, lang('code_4000'));
                }
            }

            Db::startTrans();
            try {
                EnginYueModel::where(['id'=>$param['id']])->update(['status'=>$param['status']]);

                if($param['status'] == 2){
                    $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                    $shenUserArr = (new EnginService())->get_guanuser();
                    foreach($shenUserArr as $uid){
                        (new WorkerService())->add_worker($uid, '进度月报',$enginInfo['name'], $oldInfo['id'], 'engin_yue');
                    }
                }

                (new OptService())->add_flow_log('审核', 'engin_yue', $param['id'], $statusName, $param['explain'], $param['files']);
                (new OptService())->add_log_list('审核', 'engin_yue', $param['id'], '进度月报');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function mulshen_engin_yue(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $ids = $request->post('ids','string','');

            Db::startTrans();
            try {

                $oldArr = EnginYueModel::where('id','in',$ids)->select()->toArray();
                foreach ($oldArr as $oldInfo){
                    if(!$oldInfo || $oldInfo['deleted_user'] > 0){
                        continue;
                    }

                    $statusName = '';
                    $status = $param['status'];
                    if($oldInfo['isjian'] > 0){
                        if($oldInfo['status'] == 0){
                            if( !(new EnginService())->check_is_lishen($oldInfo['enginid']) ){
                                continue;
                            }
                            $statusName = $status == 1 ? '通过[监理]' : '驳回[监理]';

                            if($status == 1){
                                $status = 2;
                            }
                        }elseif ($oldInfo['status'] == 2){
                            if( !(new EnginService())->check_is_guanshen() ){
                                if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                                    continue;
                                }
                            }
                            $statusName = $status == 1 ? '通过[管理员]' : '驳回[管理员]';
                        }else{
                            continue;
                        }
                    }else{
                        if ($oldInfo['status'] == 0){
                            if( !(new EnginService())->check_is_guanshen() ){
                                if( !(new EnginService())->check_is_jianshen($oldInfo['enginid']) ){
                                    continue;
                                }
                            }
                            $statusName = $status == 1 ? '通过[管理员]' : '驳回[管理员]';
                        }else{
                            continue;
                        }
                    }

                    EnginYueModel::where(['id'=>$oldInfo['id']])->update(['status'=>$status]);

                    if($status == 2){
                        $enginInfo = EnginModel::where(['id'=>$oldInfo['enginid']])->find();
                        $shenUserArr = (new EnginService())->get_guanuser();
                        foreach($shenUserArr as $uid){
                            (new WorkerService())->add_worker($uid, '进度月报',$enginInfo['name'], $oldInfo['id'], 'engin_yue');
                        }
                    }

                    (new OptService())->add_flow_log('审核', 'engin_yue', $oldInfo['id'], $statusName, $param['explain']);
                    (new OptService())->add_log_list('审核', 'engin_yue', $oldInfo['id'], '进度月报');
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }





    public function list_shen_bao(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bao.deleted_user','=', 0];
        $where[] = ['bao.comid','=',$this->userinfo['comid']];
        $where[] = ['e.deleted_user','=', 0];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['bao.name|user.realname','like', '%'.$param['keyword'].'%'];
        }

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['bao.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $where[] = ['bao.created_at','between', explode(' - ', $param['created_at'])];
        }


        $roleWhere = "";
        if($this->userinfo['token_roletype'] == 1){
            $roleWhere = '(bao.isjian > 0 and bao.status = 2) or (bao.isjian = 0 and bao.status = 0)';
        }else{
            $roleWhere = "(find_in_set(".$this->userinfo['dealid'].",`e`.`li_unit`) and bao.isjian > 0 and bao.status = 0)";
            $roleWhere .= " or ( find_in_set(".$this->userinfo['dealid'].",`e`.`jian_unit`) and  ( (bao.isjian > 0 and bao.status = 2) or (bao.isjian = 0 and bao.status = 0) ) )";
        }

        $data['data'] = EnginBaoModel::alias('bao')
            ->field('bao.*,user.realname as created_user_name')
            ->join('user user','user.id=bao.created_user')
            ->join('engin e','e.id=bao.enginid')
            ->where($where)
            ->where(Db::raw($roleWhere))
            ->order('bao.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['status_name'] = (new EnginService())->get_bao_status_name($item);
                $item['muid_name'] = (new EnginService())->get_mu_quanname_byid($item['muid']);
                $item['dealid_name'] = DealcomModel::where(['id'=>$item['dealid']])->value('name');
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('shen_bao');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_shen_shi(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['shi.deleted_user','=', 0];
        $where[] = ['shi.comid','=',$this->userinfo['comid']];
        $where[] = ['e.deleted_user','=', 0];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['user.realname','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['dt']) && !empty($param['dt'])){
            $where[] = ['shi.dt','between', explode(' - ', $param['dt'])];
        }

        $roleWhere = "";
        if($this->userinfo['token_roletype'] == 1){
            $roleWhere = '(shi.isjian > 0 and shi.status = 2) or (shi.isjian = 0 and shi.status = 0)';
        }else{
            $roleWhere = "(find_in_set(".$this->userinfo['dealid'].",`e`.`li_unit`) and shi.isjian > 0 and shi.status = 0)";
            $roleWhere .= " or ( find_in_set(".$this->userinfo['dealid'].",`e`.`jian_unit`) and  ( (shi.isjian > 0 and shi.status = 2) or (shi.isjian = 0 and shi.status = 0) ) )";
        }

        $data['data'] = EnginShiModel::alias('shi')
            ->field('shi.*,user.realname as created_user_name')
            ->join('user user','user.id=shi.created_user')
            ->join('engin e','e.id=shi.enginid')
            ->where($where)
            ->where(Db::raw($roleWhere))
            ->order('shi.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['enginname'] = EnginModel::where(['id'=>$item['enginid']])->value('name');
                $item['status_name'] = (new EnginService())->get_shi_status_name($item);
                $item['dealid_name'] = DealcomModel::where(['id'=>$item['dealid']])->value('name');
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('shen_shi');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_shen_jian(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['jian.deleted_user','=', 0];
        $where[] = ['jian.comid','=',$this->userinfo['comid']];
        $where[] = ['jian.status','=', 0];
        $where[] = ['e.deleted_user','=', 0];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['user.realname','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['dt']) && !empty($param['dt'])){
            $where[] = ['jian.dt','between', explode(' - ', $param['dt'])];
        }

        if($this->userinfo['token_roletype'] != 1){
            $where[] = ['jian.enginid','<', 1];
        }



        $roleWhere = "";
        if($this->userinfo['token_roletype'] == 1){
            $roleWhere = '';
        }else{
            $roleWhere = "find_in_set(".$this->userinfo['dealid'].",`e`.`jian_unit`)";
        }

        $data['data'] = EnginJianModel::alias('jian')
            ->field('jian.*,user.realname as created_user_name')
            ->join('engin e','e.id=jian.enginid')
            ->join('user user','user.id=jian.created_user')
            ->where($where)
            ->where($roleWhere)
            ->order('jian.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['enginname'] = EnginModel::where(['id'=>$item['enginid']])->value('name');
                $item['status_name'] = (new EnginService())->get_jian_status_name($item);
                $item['dealid_name'] = DealcomModel::where(['id'=>$item['dealid']])->value('name');
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('shen_jian');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_shen_yue(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['yue.deleted_user','=', 0];
        $where[] = ['yue.comid','=',$this->userinfo['comid']];
        $where[] = ['e.deleted_user','=', 0];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['user.realname','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['created_user_name']) && !empty($param['created_user_name'])){
            $where[] = ['user.realname','like', '%'.$param['created_user_name'].'%'];
        }
        if(isset($param['month']) && !empty($param['month'])){
            $where[] = ['yue.month','between', explode(' - ', $param['month'])];
        }


        $roleWhere = "";
        if($this->userinfo['token_roletype'] == 1){
            $roleWhere = '(yue.isjian > 0 and yue.status = 2) or (yue.isjian = 0 and yue.status = 0)';
        }else{
            $roleWhere = "(find_in_set(".$this->userinfo['dealid'].",`e`.`li_unit`) and yue.isjian > 0 and yue.status = 0)";
            $roleWhere .= " or ( find_in_set(".$this->userinfo['dealid'].",`e`.`jian_unit`) and  ( (yue.isjian > 0 and yue.status = 2) or (yue.isjian = 0 and yue.status = 0) ) )";
        }

        $data['data'] =EnginYueModel::alias('yue')
            ->field('yue.*,user.realname as created_user_name')
            ->join('user user','user.id=yue.created_user')
            ->join('engin e','e.id=yue.enginid')
            ->where($where)
            ->where(Db::raw($roleWhere))
            ->order('yue.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['enginname'] = EnginModel::where(['id'=>$item['enginid']])->value('name');
                $item['status_name'] = (new EnginService())->get_yue_status_name($item);
                $item['dealid_name'] = DealcomModel::where(['id'=>$item['dealid']])->value('name');
                return $item;
            })->toArray();


        $data['butauth'] = (new MenuService())->get_butauth('shen_yue');
        return outputJson(2000,lang('code_2000'),$data);
    }




    public function list_home_engin(Request $request){
        $param = $request->post();

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }

        $list = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_baoku', 'e'))
            ->order('e.id DESC')
            ->limit(6)
            ->select()->toArray();

        foreach ($list as &$item){
            $item['state_name'] = (new EnginService())->get_engin_state_name_tag($item['id'], $item['state']);
            $item['state_namemob'] = (new EnginService())->get_engin_state_name($item['id'], $item['state']);
            $item['engintype'] = (new OptService())->get_base_showname('engin_engintype', $item['engintype']);
            $item['chanfee'] = (new EnginService())->get_engin_yue_chanfee($item['id']);
        }

        $data['data'] = $list;
        $data['areas'] = (new OptService())->get_city_cader();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_home_shen(Request $request){
        $data['isshow'] = false;
        $list = [];
        $where[] = ['zhu.deleted_user','=', 0];
        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['zhu.comid','=',$this->userinfo['comid']];
        $shenEnginArr = (new EnginService())->get_lishen_engin();

        //  421 - 文件上报
        //  422 - 施工日志
        //  423 - 监理日志
        //  424 - 进度月报

        $menuIdArr = [];
        $role = UserRoleModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'type'=>$this->userinfo['token_roletype']])
            ->where('id','in', $this->userinfo['roleid'])->column('menu');
        foreach ($role as $itemMenu){
            if($itemMenu){
                $menuIdArr = array_unique(array_merge($menuIdArr, explode(',', $itemMenu)));
            }
        }

        if(in_array(421, $menuIdArr)){
            $data['isshow'] = true;
            if($this->userinfo['token_roletype'] == 1){
                $num = EnginBaoModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('(zhu.isjian > 0 and zhu.status = 2) or (zhu.isjian = 0 and zhu.status = 0)')
                    ->count();
            }else{
                $jianEnginArr = (new EnginService())->get_jian_unit_engin();
                $num = EnginBaoModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.enginid','in', $jianEnginArr)
                    ->where('(zhu.isjian > 0 and zhu.status = 2) or (zhu.isjian = 0 and zhu.status = 0)')
                    ->count();

                $shenEnginArr = (new EnginService())->get_lishen_engin();
                $num += EnginBaoModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.enginid','in', $shenEnginArr)
                    ->where('zhu.isjian > 0 and zhu.status = 0')
                    ->count();
            }
            $list[] = ['name'=>'bao','num'=>$num];
        }

        if(in_array(422, $menuIdArr)){
            $data['isshow'] = true;
            if($this->userinfo['token_roletype'] == 1){
                $num = EnginShiModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('(zhu.isjian > 0 and zhu.status = 2) or (zhu.isjian = 0 and zhu.status = 0)')
                    ->count();
            }else{
                $jianEnginArr = (new EnginService())->get_jian_unit_engin();
                $num = EnginShiModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.enginid','in', $jianEnginArr)
                    ->where('(zhu.isjian > 0 and zhu.status = 2) or (zhu.isjian = 0 and zhu.status = 0)')
                    ->count();

                $shenEnginArr = (new EnginService())->get_lishen_engin();
                $num += EnginShiModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.enginid','in', $shenEnginArr)
                    ->where('zhu.isjian > 0 and zhu.status = 0')
                    ->count();
            }
            $list[] = ['name'=>'shi','num'=>$num];
        }

        if(in_array(423, $menuIdArr)){
            $data['isshow'] = true;
            if($this->userinfo['token_roletype'] == 1){
                $num = EnginJianModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.status','=', 0)
                    ->count();
            }else{
                $jianEnginArr = (new EnginService())->get_jian_unit_engin();
                $num = EnginJianModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.enginid','in', $jianEnginArr)
                    ->where('zhu.status','=', 0)
                    ->count();
            }
            $list[] = ['name'=>'jian','num'=>$num];
        }

        if(in_array(424, $menuIdArr)){
            $data['isshow'] = true;
            if($this->userinfo['token_roletype'] == 1){
                $num = EnginYueModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('(zhu.isjian > 0 and zhu.status = 2) or (zhu.isjian = 0 and zhu.status = 0)')
                    ->count();
            }else{
                $jianEnginArr = (new EnginService())->get_jian_unit_engin();
                $num = EnginYueModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.enginid','in', $jianEnginArr)
                    ->where('(zhu.isjian > 0 and zhu.status = 2) or (zhu.isjian = 0 and zhu.status = 0)')
                    ->count();

                $shenEnginArr = (new EnginService())->get_lishen_engin();
                $num += EnginYueModel::alias('zhu')
                    ->join('engin e','e.id=zhu.enginid')
                    ->where($where)
                    ->where('zhu.enginid','in', $shenEnginArr)
                    ->where('zhu.isjian > 0 and zhu.status = 0')
                    ->count();
            }
            $list[] = ['name'=>'yue','num'=>$num];
        }

        $data['list'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }





    public function list_engin_temp(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['temp.deleted_user','=', 0];
        $where[] = ['temp.comid','=',$this->userinfo['comid']];
        $where[] = ['temp.pid','=',0];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['temp.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['temp.name','like', '%'.$param['name'].'%'];
        }

        $data['data'] = EnginTempModel::alias('temp')
            ->field('temp.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_temp', 'temp'))
            ->order('temp.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                $item['updated_user_name'] = UserModel::get_realname_by_pk($item['updated_user']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin_temp');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入模板名称');
            }
            if((new EnginService())->check_engin_temp_name($param['name'])){
                return outputJson(4000, '模板名称已存在');
            }



            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $this->userinfo['id'];
            $param['created_at'] = date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();
            unset($param['token']);


            Db::startTrans();
            try {
                $id = EnginTempModel::insertGetId($param);
                EnginTempModel::where(['id'=>$id])->update(['topid'=>$id,'parents'=>$id]);

                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_temp', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_temp', $id, '资料库模板');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data = [];
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入模板名称');
            }
            if((new EnginService())->check_engin_temp_name($param['name'], $param['id'])){
                return outputJson(4000, '模板名称已存在');
            }


            unset($param['token']);


            Db::startTrans();
            try {
                EnginTempModel::update($param);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_temp', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_temp', $param['id'], '资料库模板');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginTempModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function copy_engin_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入模板名称');
            }
            if((new EnginService())->check_engin_temp_name($param['name'])){
                return outputJson(4000, '模板名称已存在');
            }


            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $this->userinfo['id'];
            $param['created_at'] = date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();

            $copyid = $param['id'];
            unset($param['id']);
            unset($param['token']);


            Db::startTrans();
            try {
                $id = EnginTempModel::insertGetId($param);
                EnginTempModel::where(['id'=>$id])->update(['topid'=>$id,'parents'=>$id]);

                $this->temp_copy_temp($copyid, $id);

                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_temp', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_temp', $id, '资料库模板');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginTempModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function temp_copy_temp($copyid, $pasteid){
        $copyInfo = EnginTempModel::where(['id'=>$copyid])->find();
        $pasteInfo = EnginTempModel::where(['id'=>$pasteid])->find();

        if($copyInfo['pid'] > 0){
            //复制文件夹
            $maxSort = EnginTempModel::where(['pid'=>$pasteInfo['id'],'deleted_user'=>0])->max('sort');
            $pasteArr = [
                'comid' => $pasteInfo['comid'],
                'pid' => $pasteInfo['id'],
                'topid' => $pasteInfo['topid'],
                'parents' => $pasteInfo['parents'],
                'level' => $pasteInfo['level']+1,
                'sort' => (int)$maxSort+1,
                'ismu' => $copyInfo['ismu'],
                'name' => (new EnginService())->check_temp_name($copyInfo['name'], $pasteInfo['id']),
                'ext' => $copyInfo['ext'],
                'size' => $copyInfo['size'],
                'oripath' => $copyInfo['oripath'],
                'encpath' => $copyInfo['encpath'],
                'created_user' => $this->userinfo['id'],
                'updated_user' => $this->userinfo['id'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            $pasteNewId = EnginTempModel::insertGetId($pasteArr);
            $pasteNewParents = $pasteArr['parents'].','.$pasteNewId;
            if($copyInfo['ismu'] > 0){
                $encpath =  encrypt($pasteNewId, 'E', Config::get('service.info_key'));
                EnginTempModel::where(['id'=>$pasteNewId])->update(['parents'=>$pasteNewParents,'encpath'=>$encpath]);
            }else{
                EnginTempModel::where(['id'=>$pasteNewId])->update(['parents'=>$pasteNewParents]);
            }
        }else{
            $pasteNewId = $pasteInfo['id'];
        }



        //处理子级
        $childrenArr = EnginTempModel::where(['pid'=>$copyid,'deleted_user'=>0])->select()->toArray();
        foreach ($childrenArr as $chilitem){
            $this->temp_copy_temp($chilitem['id'], $pasteNewId);
        }
    }

    public function del_engin_temp(Request $request){
        $param = $request->post();
        $data = EnginTempModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            EnginTempModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_temp', $data['id'], '资料库模板');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function list_temp_list(Request $request){
        $tempid = $request->param('tempid', 0, 'int');
        $muid = $request->param('muid', 0, 'int');
        $muid_Parents = EnginTempModel::where(['id'=>$muid])->value('parents');
        $sppaarr = explode(',', $muid_Parents);

        $data = EnginTempModel::field('id,pid,name as title, parents,ismu,ext,size,oripath,encpath')
            ->where(['comid'=>$this->userinfo['comid'],'topid'=>$tempid,'deleted_user'=>0])
            ->order('pid ASC, ismu ASC, sort ASC')->select()->toArray();

        foreach ($data as &$item){
            if(in_array($item['id'], $sppaarr)){
                $item['spread'] = true;
            }
//            $parentsName = (new EnginService())->get_temp_quanname($item['parents'], 1);
            $parentsName = '';
            $item['basicData'] = [
                'id'=>$item['id'],
                'pid'=>$item['pid'],
                'name'=>$item['title'],
                'ismu'=>$item['ismu'],
                'part'=>'dept',
                'parentsName'=>$parentsName,
                'ext'=>$item['ext'],
                'size'=>$item['size'],
                'oripath'=>$item['oripath'],
                'encpath'=>$item['encpath'],
            ];
            if($item['ismu'] > 0){
                $item['basicData']['noicon'] = 1;
                $item['title'] = '<span class="colorhong">【模板】</span>'.$item['title'];
            }
        }
        $data = array_values(listToTree($data));


        return json_encode([
            'status'=>['code'=>200,'message'=>"操作成功"],
            'data'=>$data,
            'code'=>2000,
            'msg'=>'请求成功',
        ]);
    }
    public function list_temp_list222(Request $request){
        $tempid = $request->param('tempid', 0, 'int');
        $muid = $request->param('muid', 0, 'int');
        $muid_Parents = EnginTempModel::where(['id'=>$muid])->value('parents');
        $sppaarr = explode(',', $muid_Parents);


        $data = EnginTempModel::field('id,pid,name as title, parents,ismu')->where(['id'=>$tempid])->find();
        if(in_array($data['id'], $sppaarr)){
            $data['spread'] = true;
        }
        $parentsName = (new EnginService())->get_temp_quanname($data['parents'], 1);
        $data['basicData'] = ['id'=>$data['id'],'pid'=>$data['pid'],'name'=>$data['title'],'ismu'=>$data['ismu'],'part'=>'dept','parentsName'=>$parentsName];
        $data['children'] = (new EnginService())->get_temp_sons($tempid, $sppaarr);


        return json_encode([
            'status'=>['code'=>200,'message'=>"操作成功"],
            'data'=>[$data],
            'code'=>2000,
            'msg'=>'请求成功',
        ]);
    }
    public function add_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidInfo = EnginTempModel::where(['id'=>$param['pid']])->find();
            $param['name'] = (new EnginService())->check_temp_name($param['name'], $param['pid']);
            $param['topid'] = $pidInfo['topid'];
            $param['level'] = $pidInfo['level'] + 1;
            $param['sort'] = (int)$param['sort'];
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);

            $tempid = $param['tempid'];
            unset($param['tempid']);

            Db::startTrans();
            try {
                $id = EnginTempModel::insertGetId($param);

                $newParents = $pidInfo['parents'].','.$id;
                EnginTempModel::where(['id'=>$id])->update(['parents'=>$newParents]);

                EnginTempModel::where(['id'=>$tempid])->update(['updated_user'=>$param['updated_user'],'updated_at'=>$param['updated_at']]);


                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_temp', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_temp', $id, '文件夹');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $pid = $request->param('pid',0, 'int');
            $pidInfo = EnginTempModel::where(['id'=>$pid])->find();
            $data['pid_name'] = (new EnginService())->get_temp_quanname($pidInfo['parents'], 1);
            $sort = EnginTempModel::where(['comid'=>$this->userinfo['comid'],'pid'=>$pid,'deleted_user'=>0])
                ->order('sort DESC')->value('sort');
            $data['sort'] = ceil($sort)+1;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $oldInfo = EnginTempModel::where(['id'=>$param['id']])->find();
            $param['name'] = (new EnginService())->check_temp_name($param['name'], $oldInfo['pid'], $param['id']);
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $param['sort'] = (int)$param['sort'];
            unset($param['token']);

            $tempid = $param['tempid'];
            unset($param['tempid']);

            Db::startTrans();
            try {
                EnginTempModel::update($param);

                EnginTempModel::where(['id'=>$tempid])->update(['updated_user'=>$param['updated_user'],'updated_at'=>$param['updated_at']]);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_temp', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_temp', $param['id'], '文件夹');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data = EnginTempModel::where(['id'=>$id])->find();
            if(!$data){
                return outputJson(4000, lang('code_4000'));
            }
            $pidInfo = EnginTempModel::where(['id'=>$data['pid']])->find();
            $data['pid_name'] = (new EnginService())->get_temp_quanname($pidInfo['parents'], 1);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function shang_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $muinfo = EnginTempModel::where(['id'=>$param['id']])->find();
            $list = EnginTempModel::field('id,sort')
                ->where(['comid'=>$this->userinfo['comid'],'pid'=>$muinfo['pid'],'deleted_user'=>0])
                ->order('ismu ASC,sort ASC,id ASC')->select()->toArray();


            Db::startTrans();
            try {
                foreach ($list as $k=>$v){
                    $v['sort'] = $k+1;
                    EnginTempModel::where(['id'=>$v['id']])->update(['sort'=>$v['sort']]);
                }

                $updmuinfo = EnginTempModel::where(['id'=>$param['id']])->find();
                if($updmuinfo['sort'] != 1){
                    $shangmuinfo = EnginTempModel::where(['pid'=>$muinfo['pid'],'deleted_user'=>0,'sort'=>$updmuinfo['sort']-1])->find();
                    EnginTempModel::where(['id'=>$shangmuinfo['id']])->update(['sort'=>$updmuinfo['sort']]);
                    EnginTempModel::where(['id'=>$updmuinfo['id']])->update(['sort'=>$shangmuinfo['sort']]);
                }



                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function xia_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $muinfo = EnginTempModel::where(['id'=>$param['id']])->find();
            $list = EnginTempModel::field('id,sort')
                ->where(['comid'=>$this->userinfo['comid'],'pid'=>$muinfo['pid'],'deleted_user'=>0])
                ->order('ismu ASC,sort ASC,id ASC')->select()->toArray();


            Db::startTrans();
            try {
                foreach ($list as $k=>$v){
                    $v['sort'] = $k+1;
                    EnginTempModel::where(['id'=>$v['id']])->update(['sort'=>$v['sort']]);
                }

                $updmuinfo = EnginTempModel::where(['id'=>$param['id']])->find();
                if($updmuinfo['sort'] != count($list)){
                    $xiamuinfo = EnginTempModel::where(['pid'=>$muinfo['pid'],'deleted_user'=>0,'sort'=>$updmuinfo['sort']+1])->find();
                    EnginTempModel::where(['id'=>$xiamuinfo['id']])->update(['sort'=>$updmuinfo['sort']]);
                    EnginTempModel::where(['id'=>$updmuinfo['id']])->update(['sort'=>$xiamuinfo['sort']]);
                }



                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function del_temp(Request $request){
        $param = $request->post();
        $data = EnginTempModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }
//
//        $existSon = EnginTempModel::where(['pid'=>$data['id'],'deleted_user'=>0])->find();
//        if($existSon){
//            return outputJson(4000, '该目录存在下级目录/模板，无法删除');
//        }


        Db::startTrans();
        try {
            EnginTempModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            //删除子级
            EnginTempModel::where(Db::raw("find_in_set(".$data['id'].",`parents`)"))->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_temp', $data['id'], '文件夹');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function chuan_temp(Request $request)
    {
        $muid = $request->param('muid',0,'int');
        $muidinfo = EnginTempModel::where(['id'=>$muid])->find();
        if($muidinfo['pid'] < 1){
            return outputJson(4000, '该文件夹无法上传模板,请重新上传');
        }

        $maxSort = EnginTempModel::where(['pid'=>$muid,'deleted_user'=>0])->max('sort');

        $files = request()->file('files');


        try{
            foreach ($files as $file){
                $fileInfo = $file->getInfo();
                $filesize = round($fileInfo['size']/1024,2);
                $info = $file->validate([
                    'size'=>Config::get('service.upload.size'),'ext'=>Config::get('service.upload.ext')
                ])->move($this->movePath);

                if($info){
                    $ins = [];
                    $ins['comid'] = $this->userinfo['comid'];
                    $ins['deptid'] = $this->userinfo['deptid'];
                    $ins['chanid'] = (new UserService())->get_user_chanid();
                    $ins['pid'] = $muidinfo['id'];
                    $ins['topid'] = $muidinfo['topid'];
                    $ins['parents'] = $muidinfo['parents'];
                    $ins['level'] = $muidinfo['level'] + 1;
                    $ins['sort'] = (int)$maxSort + 1;
                    $ins['ismu'] = 1;

                    $ins['name'] = $fileInfo['name'];
                    $ins['ext'] =  strtolower($info->getExtension());
                    $ins['size'] = $filesize;
                    $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                    $ins['created_user'] =  $this->userinfo['id'];
                    $ins['created_at'] =  date('Y-m-d H:i:s');
                    $ins['updated_at'] =  date('Y-m-d H:i:s');
                    $ins_id = EnginTempModel::insertGetId($ins);

                    $newParents = $muidinfo['parents'].','.$ins_id;
                    $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                    if(EnginTempModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath,'parents'=>$newParents]) === false){
                        throw new Exception("上传失败");
                    }

                    (new OptService())->add_flow_log('上传模板', 'engin_temp', $ins_id);
                    (new OptService())->add_log_list('上传模板', 'engin_temp', $ins_id, '文件资料库');
                }else{
                    throw new Exception("上传失败");
                }
            }
        }catch (\Exception $e){
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function paste_temp(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $copyInfo = EnginTempModel::where(['id'=>$param['copyid']])->find();
            $pasteInfo = EnginTempModel::where(['id'=>$param['pasteid']])->find();
            if($copyInfo['pid'] < 1 || $copyInfo['ismu'] > 0 || $pasteInfo['ismu'] > 0){
                return outputJson(4000,lang('code_4000'));
            }

            Db::startTrans();
            try {
                $this->paset_chu_temp($param['copyid'], $param['pasteid'], $param['datatype']);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(4000,lang('code_4000'));
    }
    public function paset_chu_temp($copyid, $pasteid, $datatype){
        $copyInfo = EnginTempModel::where(['id'=>$copyid])->find();
        $pasteInfo = EnginTempModel::where(['id'=>$pasteid])->find();
        //复制文件夹
        $maxSort = EnginTempModel::where(['pid'=>$pasteInfo['id'],'deleted_user'=>0])->max('sort');
        $pasteArr = [
            'comid' => $pasteInfo['comid'],
            'pid' => $pasteInfo['id'],
            'topid' => $pasteInfo['topid'],
            'parents' => $pasteInfo['parents'],
            'level' => $pasteInfo['level']+1,
            'sort' => (int)$maxSort+1,
            'ismu' => $copyInfo['ismu'],
            'name' => (new EnginService())->check_temp_name($copyInfo['name'], $pasteInfo['id']),
            'ext' => $copyInfo['ext'],
            'size' => $copyInfo['size'],
            'oripath' => $copyInfo['oripath'],
            'encpath' => $copyInfo['encpath'],
            'created_user' => $this->userinfo['id'],
            'updated_user' => $this->userinfo['id'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        $pasteNewId = EnginTempModel::insertGetId($pasteArr);
        $pasteNewParents = $pasteArr['parents'].','.$pasteNewId;
        if($copyInfo['ismu'] > 0){
            $encpath =  encrypt($pasteNewId, 'E', Config::get('service.info_key'));
            EnginTempModel::where(['id'=>$pasteNewId])->update(['parents'=>$pasteNewParents,'encpath'=>$encpath]);
        }else{
            EnginTempModel::where(['id'=>$pasteNewId])->update(['parents'=>$pasteNewParents]);
        }


        if($datatype == 'cut'){
            EnginTempModel::where(['id'=>$copyid])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
        }


        //处理子级
        $childrenArr = EnginTempModel::where(['pid'=>$copyid,'deleted_user'=>0])->select()->toArray();
        foreach ($childrenArr as $chilitem){
            $this->paset_chu_temp($chilitem['id'], $pasteNewId, $datatype);
        }
    }
    public function edit_temp_ban(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $oldInfo = EnginTempModel::where(['id'=>$param['id']])->find();

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                if($param['fileid']){
                    $fileinfo = FileModel::where(['id'=>$param['fileid']])->find();

                    $param['name'] = $param['name'].'.'.$fileinfo['ext'];
                    $param['ext'] = $fileinfo['ext'];
                    $param['size'] = $fileinfo['size'];
                    $param['oripath'] = $fileinfo['oripath'];
                    $param['encpath'] = encrypt($param['id'], 'E', Config::get('service.info_key'));
                }else{
                    $param['name'] = $param['name'].'.'.$oldInfo['ext'];
                }

                EnginTempModel::update($param);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_temp', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_temp', $param['id'], '资料库模板');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }

            $returninfo = EnginTempModel::where(['id'=>$param['id']])->find();
            $returninfo['parentsName'] = (new EnginService())->get_temp_quanname($returninfo['parents'], 1);
            return outputJson(2000,lang('code_2000'),['data'=>$returninfo]);
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginTempModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['data']['name'] = mb_substr($data['data']['name'], 0, mb_strlen($data['data']['name'])-4);

            $data['data']['pid_name'] = (new EnginService())->get_temp_quanname($data['data']['parents']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

















}
